The Ideal WP_Query Loop

Updated reading time

When it comes to building a custom WP_Query loop, it comes easily that you would be checking for results from stackoverflow, some websites, and possibly just blagging to get it working properly. Yes, WP_Query is one of the best ways to create a custom query, but below will save the hassle of you finding through to optimise your WP_Query (any questions let me know in the comments below the article):

Dissecting the Code

Simply put, a PHP variable is created for a new WP_Query, with the following arguments listed in its own $args variable, to keep things nice and tidy. What is being asked for is what you are essentially ‘querying’ or ‘asking a question’ about towards the WordPress database of your website.

WP_Query post_type

In the example code listed earlier, it would be querying a set of 10 posts from a Custom Post Type. To make the query faster, we will only need the ID of each at the very minimum. If you would like to easily create Custom Post Types for your clients’ websites, you may want to have a look at installing the plugin CPTUI by WebDevStudios.

WP_Query post_status

Of course, we would like to make sure that only published articles are showing. We don’t need to display this though. But it would not cost the Earth to keep it either. It displays the post_status succinctly, which is ideal if another web developer were to chime in with the code.

WP_Query orderby

This is the same in that we would like to express through the code that we would like to list down the query in chronological order. Again please feel free to have a look at the defaults found in the WordPress official documentation for WP_Query.

WP_Query posts_per_page

posts_per_page in a default WordPress installation will output 10 posts in a loop. This could be explicitly set to 10, to be sure that 10 will always be displayed even if the settings are changed in the back-end of the website.

WP_Query no_found_rows, and remaining fields

For the remaining 4 arguments, they have been taken from the rest of the internet! Kinsta provides a good article on this from which has been adopted.

Outputting the WP_Query Code

Sections have been used to signify that this can be a reusable section. But any other appropriate element may be used. Please note that an id attribute is meant to add more context towards the section, as well as making the section anchorable through the id attribute. The while loop does its work, and we end with wp_reset_postdata() to tidy up the WP_Query that was performed.

Any issues please let me know in the comments below!