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.

$posts = get_posts( $args );
foreach( $posts as $post ) : setup_postdata( $post );

// Do stuff

wp_reset_postdata(); endforeach;

Versus this:

$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post();

// Do stuff

endwhile; endif;

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).

$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!

$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? :)

How to release a WordPress plugin

About a month ago, I finally released my plugin Responsify WP on It was a fairly simple process, even though it was my first time doing this. But as always in this business, there were moments when I found myself asking Google for help. Therefore I decided to write this little guide on how to publish a WordPress plugin.

Continue reading How to release a WordPress plugin