How to use WP_Query for a new loop in WordPress

If you think you have a situation where you want to show a certain set of your WordPress content and you have tried to find a solution with the existing possibilities in WordPress but you can not make it work you can add your own “loop” and display the content you like.

Think about it twice

Before jumping right into the details of setting up a custom loop in WordPress really try to make sure that what you are trying to do can not easily be accomplished with existing functionality in WordPress. Let’s say you want to show only a subset of your posts on a page. Use categories for this. If categories don’t seem to fit simply assign special tags to the desired content and use tags instead. The search is powerful as well and you can construct search URLs for your WordPress website that selects and displays the right content. Most of the time you do not have to change your theme for that.

Valid use cases

But let’s say your use case is special and for example you created a custom post type for, let’s say, cars. If you then want to select only certain brands and vehicles with a given color and want to use that content either in a special location of your theme or you want to publish that data in the WordPress REST API or want to send a report by e-mail then WP_Query is your friend.

WP_Query is a very powerful class in WordPress that can take a lot of different parameters to select the content you want. The basic code looks like this:

<?php

$query = new WP_Query( 
           array( 'post_type' => 'post', 'nopaging' => true )
         );
while ( $query->have_posts() ) :
  $query->the_post();
  $post = $query->post;
	
  #
  # Do something with $post ...
  #
endwhile;

You create a new WP_Query object and supply an array that holds the necessary parameters. You then loop over the results and can work on the individual objects.

There are a lot of parameters and of course it highly depends on your use case which ones you might have to use. Check out the very detailed documentation on wordpress.org for more information.

Quick start

If you want to have a quick start you can use the code generator over at generatewp.com. The WP_Query generator comes with a variety of parameters and you can generate the necessary code by selecting what fits your scenario. At the end you can just copy the generated code over into your plugin or theme file that you are working on.