What is: WP_Query

Keeping in mind that all of the software powering WordPress is written in the PHP programming language, wp_query is a way for developers to perform certain things such as creating custom queries that deal with class references for posts and pages.

 

As this is a powerful tool, using wp_query is recommended for professional developers only.

 

The command wp_query, just as you might expect, performs a query of the WordPress database. For example, here’s a very basic wp_query that will return only posts that fall into the movies category:

<?php
// The Query
$the_query = new WP_Query( 'category_name=movies' );
 
?>

 

Keep in mind that the above code will not (automatically) display the relevant posts. In order to do that, you need to write a more complicated wp_query like this:

<?php
// The Query
$the_query = new WP_Query( 'category_name=movies' );
 
// The Loop
if ( $the_query->have_posts() ) {
        echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
        echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
 
?>

 

The wp_query is a very versatile and powerful code and can be used to write very complex queries. You can also use wp_query to create nested loops. The wp_query query is very useful for creating plugins and themes in order to create custom ways for posts (and pages) to be displayed.

The following two tabs change content below.

Jamie Spencer

My name is Jamie Spencer and I have spent the past 10 years building money making blogs. After growing tired of the 9-5, commuting and never seeing my family I decided that I wanted to make some changes and launched my first blog. Since then I have launched lots of successful niche blogs and after selling my survivalist blog I decided to teach other people how to do the same.