I have this very simple Wordpress while loop:
$loop = new WP_Query( args ) );
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
echo $data;
echo "<br/";
endwhile;
This gives me something like:
datastring1
datastring2
anotherdata
somethingelse
and else
and so forth
(...)
I want to save these values from while loop as an array or variables, eg.
$data1 = "datastring1";
$data2 = "datastring2";
$data3 = "anotherdata";
(...)
How to? :)
Thanks!
You can save in array easily
$array=array();
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
$array[]=$data;
endwhile;
print_r($data);
$array will store data from index 0 to the number of elements while loop iterate
Use a counter $i to keep track of the number, and then you can save the results either as an array or as a set of variables.
$loop = new WP_Query( args ) );
$i = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
$i++;
$array[] = $data; // Saves into an array.
${"data".$i} = $data; // Saves into variables.
endwhile;
You only need to use the $i counter if you use the second method. If you save into an array with the above syntax, the indexes will be generated automatically.
Related
I have a working wordpress loop which displays all posts of a certain meta_query value. The only issue is that the values are repeated. For example, if I have two posts with the value "Blue" then both posts appear in the loop, which makes "Blue" appear twice.
What I would like is for "Blue" to appear once, and underneath it, a list of all post titles with that value.
Here's my current query:
<?php
$the_query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'colors',
));
while ( $the_query->have_posts() ) : $the_query->the_post();
$colors = get_field('colors');
if( $colors ): foreach( $colors as $color ):
endforeach;
endif;
echo' <div><h2>'.$color.'</h2><div>'.get_the_title( $post_id ).'</div></div>';
endwhile; wp_reset_postdata();?>
I tried using an array for the titles, but it just returned "Array"
$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}
echo $title_names
I'm thinking I need another if statement somewhere with an array? Or maybe I'm approaching this from the wrong direction.
You would want to try something like this:
$results = [];
while ( $the_query->have_posts() ) {
$the_query->the_post();
$colors = get_field('colors');
if( !empty($colors) ) {
foreach( $colors as $color ) {
$results [$color][]['title'] = get_the_title();
$results [$color][]['link'] = get_attachment_link();
}
}
}
foreach ($results as $color => $posts) {
echo "<div><h2>{$color}<h2>";
foreach($posts as $post) {
echo "<div>{$post['title']}</div>";
}
echo '</div>';
}
I have a loop that gets all the posts that are "custom_post". It works perfectly - apart from that when I echo a variable it duplicates the variable when there are more than one post.
Its hard to explain - but basically if I have one post it works perfectly. I get a Div with the class name that is assigned to that custom post.
When I add another post - again that works, but displays two divs with the second post. I would imagine that it has something to do with echo $variable in the loop.
Any ideas? Thanks
EDIT
CODE:
function display_css() {
$ids = array();
$args = array( 'post_type' => 'custom_post');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
array_push( $ids, get_the_ID() );
endwhile;
foreach (array_unique($ids) as $key => $value) {
$check_select_modules = $titan->getOption( 'selec_modules', $value );
if ( "accordianmodule" == $check_select_modules) {
include(DE_DB_PATH . '/lib/modules/accordian.php');
}
elseif ( "textmodule" == $check_select_modules) {
include(DE_DB_PATH . '/lib/modules/text.php');
}
else {
}
}
}
add_action( 'wp_head', 'display_css', 15 );
Then in one of the php scripts it has
$css_accordian .= '<style id="css-'.$accordian_module_heading_css_class_display.'">';
echo $css_accordian;
I get the variable $accordian_module...... further up the script.
First of all you miss a quote here:
$variable .= '<div class"'.$classname.;">;
should be:
$variable .= '<div class"'.$classname.'">';
Suggestion:
$ids = array();
$args = array( 'post_type' => 'custom_post');
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
array_push($ids, get_the_ID());
}
}
However.. instead of using a foreach to loop through all the ID's for a second time, why you not echo a div in side the loop above, like this:
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) {
$loop->the_post();
echo '<div class="'.$classname.'">' . the_ID() . '</div>';
}
}
Or do you want one div where all the posts are shown?
The problem is that $classname is not being set in that piece of code you have copied here. I'm guessing it gets assigned some value before this code?
I recommend set the classname into the $ids array (though you should call that something else then) during the while loop. something like this, though "$post->classname" probably won't work, you'll have to figure out where to get classname from.
while ( $loop->have_posts() ) : $loop->the_post();
$ids[get_the_ID()] = $post->classname;
endwhile;
Then in the for loop, the $value will contain your classname, so you can do this:
foreach (array_unique($ids) as $key => $value) {
$variable ='<div class"'.$value.;">;
echo $variable;
}
I've been asked by a client to implement a new search feature in lieu of a custom Google search engine that kept displaying old results due to caching issues. Ironically, a solution to this question may result in a similar issue, but I'll deal with that when I get to it :).
The search code I've implemented is as follows:
<?php
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
$the_query = new WP_Query($search_query);
if ( $the_query->have_posts() ) :
?>
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php echo esc_attr( $post->post_title ); ?>
<?php endwhile; ?>
<!-- end of the loop -->
<?php wp_reset_postdata(); ?>
This query is super slow. I know the current code runs a specific WP_Query based on the $search_query, but is there a way to cache the post data every so often to minimize queries to the database, and then compare search terms against those data?
You could use the WP_Object_Cache.
Do something like:
global $query_string;
// Check the existing cache for this query
$post_ids = wp_cache_get( $query_string );
// If cache does not exist
if ( false === $post_ids ) {
// Create the query
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
}
//This is the super slow query.
$the_query = new WP_Query($search_query);
//Grab the ID:s so we can make a much more lightweight query later
$post_ids = wp_list_pluck( $the_query->posts, 'ID' );
//Cache it!
wp_cache_set($query_string, $post_ids);
$posts = $the_query->posts;
} else {
$the_query = new WP_Query(array(
'post__in' => $post_ids,
));
while($the_query->have_posts()) {
// loop here
}
}
This will get the query string as you were previously then save that query string to the WP Object Cache. We check for that query string in the cache, if it is not found then we run the query and save the results, if it is found, loop through the posts.
The queries will run slow the first time they are ran, but will speed up as they are cached.
Here is an example loop:
$args = array('s' => 'Example search term', 'cat' => 100, 'posts_per_page' => -1);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) { $query->the_post();
foreach((get_the_category()) as $category) {
echo $category->cat_name . '<br />';
}
}
}
wp_reset_query();
Assuming that the category with the id# 100 is a parent category for several subcategories, this loop successfully returns a list of heavily duplicated category names.
How could I list only unique category names and count them? And put both values into appropriate variables.
Along with the complete list of all found results and their count, too...
Of course I'll try to figure out the solution myself while waiting for your kind answer, as always. But, actually, a little help would be much appreciated.
So, I'll respond to myself. Again )
Thanks to #Perumal93's hint which directed me the correct way, I now have the solution.
In case it would be usable for anyone like me, here is the commented code ready for copy and paste:
$args = array('s' => 'Example search term', 'cat' => 100, 'posts_per_page' => -1);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
$categories = array(); // 1. Defining the empty array outside of the loop
while ( $query->have_posts() ) { $query->the_post();
foreach((get_the_category()) as $category) {
$categories[] = $category->cat_name; // 2. Filling the array with required data
}
}
$u_categories = array_unique($categories); // 3. Clearing the array from repeated data
$u_categories_cnt = count($u_categories); // 4. Counting the cleared array items
foreach( $u_categories as $category ) { // 5. Outputting
if($category == end($u_categories)) { echo $category.'.'; } // the cleared
elseif($category == prev($u_categories)) { echo $category.' and '; } // array in a
else {echo $category.', '; } // human
} // friendly way
echo $u_categories_cnt; // 6. Outputting the cleared array items count
}
wp_reset_query();
That's it
I want to create multidimensional array inside function and then access it outside function. Right now I have this function:
function custom_shop_array_create($product, $counter){
$product_id = get_the_ID();
$product_title = get_the_title($product_id);
$products_arr[]['id'] = $product_id;
$products_arr[]['title'] = $product_title;
$products_arr[]['price'] = $product->get_price();
$products_arr[]['image'] = get_the_post_thumbnail($product_id, 'product-list-thumb', array('class' => 'product-thumbnail', 'title' => $product_title));
return $products_arr;
}
and it is called inside this code:
$products_arr = array();
if ( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post();
custom_shop_array_create($product);
endwhile;
endif;
the problem is that I cant access $products_arr. I have tried replacing custom_shop_array_create($product); with $my_array[] = custom_shop_array_create($product); but then I get 3 dimensional array. So is there any way to get 2 dimensional array that would look like this:
product 1 (id,title,price,image)
product 2 (id,title,price,image) etc.
outside of the function.
Thanks in forward
Sure. Make your function return a row of the final array and do the appending yourself:
function custom_shop_array_create($product, $counter){
$product_id = get_the_ID();
$product_title = get_the_title($product_id);
return [
'id' => $product_id,
'title' => $product_title,
// etc
];
}
And then:
$products_arr = array();
if ( $products->have_posts() ) :
while ( $products->have_posts() ) :
$products->the_post();
$products_arr[] = custom_shop_array_create($product);
endwhile;
endif;
That said, something strange is going on in the while loop. What does $products->the_post() do? Where is $product coming from?