How to use a foreach loop with WP_Query
I prefer to use the get_posts()
function when fetching content outside the regular loop in WordPress. I think it’s much cleaner than creating a new instance of the WP_Query
class.
<?php
$posts = get_posts( $args );
foreach( $posts as $post ) : setup_postdata( $post );
// Do stuff
wp_reset_postdata(); endforeach;
?>
Versus this:
<?php
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();
// Do stuff
endwhile; endif;
wp_reset_query();
?>
There are times however when get_posts()
can’t do all the things that WP_Query
can. One example is that get_posts()
can’t make a query based on a search string (for some reason).
<?php
$search_string = get_search_query();
// Won't work
get_posts( array( 's' => $search_string ) );
// Will work
new WP_Query( array( 's' => $search_string ) );
?>
But there is still a way to loop through the posts without the ugly, regular WordPress loop, even when using WP_Query
. You see, the WP_Query
object has a get_posts()
method!
<?php
$posts = new WP_Query( array( 's' => $search_string ) );
$posts = $posts->get_posts();
foreach( $posts as $post ) { /* ... */ }
?>
Isn’t it nice to be able to use a foreach
loop instead of the dirty and ugly standard WordPress loop? :)