Trusted WordPress tutorials, when you need them most.
Beginner’s Guide to WordPress
WPB Cup
25 Million+
Websites using our plugins
16+
Years of WordPress experience
3000+
WordPress tutorials
by experts

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

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience in WordPress, Web Hosting, eCommerce, SEO, and Marketing. Started in 2009, WPBeginner is now the largest free WordPress resource site in the industry and is often referred to as the Wikipedia for WordPress.

The Ultimate WordPress Toolkit

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