Beginner's Guide for WordPress / Start your WordPress Blog in minutes

What is: WP_Query

WP_Query is a class defined in WordPress. It allows developers to write custom queries and display posts using different parameters. It is possible for developers to directly query WordPress database. However, WP_Query is one of the recommended ways to query posts from WordPress database.

Below is an example of a simple WP_Query which displays posts from movies category:

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

?>

The sample code above does not automatically display posts. To display results of the query, user would need to use the WordPress loop. 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();

?>

WP_Query is a powerful tool there are many parameters that can be used to write more complex and advance queries. WP_Query can be used to create nested loops (a WordPress loop inside a loop). WordPress developers can use it in their plugins and themes to create their own custom displays of posts.

A full list of WP_Query parameters is available on WordPress Codex.

Additional Reading

The Ultimate WordPress Toolkit

Get FREE access to our toolkit - a collection of WordPress related products and resources that every professional should have!