WordPress Query 101: WP_Query vs query_posts() vs get_posts()

Published on
byRanuka
Facebook
Twitter
LinkedIn

In WordPress, there are three different functions for querying posts: WP_Query, query_posts(), and get_posts(). While all three of these functions can be used to fetch posts, they each have their own unique features and should be used in different situations.

WordPress Query

What is WP_Query?

This is the most flexible and powerful way to query posts in WordPress. It allows you to retrieve posts based on any number of parameters, including custom fields, taxonomies, post type, and more. It returns an instance of the WP_Query class, which you can then loop through to display the posts. WP_Query is the recommended way to query posts in WordPress and should be used in most cases where you need to customize the query.

$args = array(
    'post_type' => 'post',
    'posts_per_page' => 10,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Display post content
    }
    wp_reset_postdata();
}

What is query_posts()?

This function is similar to WP_Query but is not recommended to use because it modifies the main query, which can lead to unexpected results, and is not recommended for use in WordPress themes or WordPress plugins. It is mainly used by developers to modify the main query on a specific page or archive.

query_posts('category_name=featured&posts_per_page=5');
if (have_posts()) {
  while (have_posts()) {
    the_post();
    // Display post content
  }
}
wp_reset_query();

What is get_posts()?

This function is similar to WP_Query, but it returns an array of posts rather than an instance of the WP_Query class. It is useful when you need to retrieve a set of posts but don’t need the full flexibility of WP_Query. Like WP_Query, get_posts() allows you to specify any number of parameters to filter the posts that are retrieved.

$args = array(
  'post_type' => 'page',
  'posts_per_page' => -1,
  'post_status' => 'publish',
);
$pages = get_posts($args);
foreach($pages as $page) {
  // Display page content
}

WP_Query vs query_posts() vs get_posts()

Rarst has created the following awesome diagram to understand it with visuals.

In summary, WP_Query is the most flexible and powerful way to query posts and should be used in most cases. query_posts() should be avoided as it can lead to unexpected results, while get_posts() is useful when you need to retrieve a set of posts but don’t need the full flexibility of WP_Query.