How to write optimized WP_Query in WordPress[2 example]?

WordPress comes with lots of built-in functionalities. And one of the most used functionality is the WP_Query class. We play around WP_Query every day. Today let’s see how to write optimized WP_Query in WordPress?

What is WP_Query?

WP_Query is WordPress’s default PHP class to create queries for posts, pages, custom post types, authors, and many more. With the help of WP_Query, we do not need to write a separate database query for our needs. It allows us to build a complex search from the database and give the response.

WP_Query is used with the loop. WP_Query has many arguments to build a query that sometimes makes it heavy to search. That’s why today we will see how to use WP_Query class efficiently and write an optimized way.

WP_Query default structure

We can use WP_Query by creating an instance of the class with the required arguments $args. You must pass the arguments in $args to fetch the data.

<?php
// WP_Query
$query = new WP_Query( $args );

if ( $query->have_posts() ) :

	while ( $query->have_posts() ) : $query->the_post();
	?>
		<h2><?php the_title(); ?></h2>
	<?php
	endwhile;

	wp_reset_postdata();

else:
	// No any post found!
endif;
?>

Get the recent 5 posts

Now let’s see about the arguments in some detail, and how can you use them. We will get the recent 5 posts with WP_Query.

<?php
// WP_Query

$args = [
    'post_type'      => 'post',
    'post_status'    => 'publish',
    'posts_per_page' => '5',
    'orderby'        => 'date',
    'order'          => 'DESC',
];

$query = new WP_Query( $args );

if ( $query->have_posts() ) :

	while ( $query->have_posts() ) : $query->the_post();
	?>
		<div class="posts-wrap">
			<h2><?php the_title(); ?></h2>
		</div>
	<?php
	endwhile;

	wp_reset_postdata();

else:
	// No any post found!
endif;
?>

In the above example, we have used multiple arguments to get 5 recent posts. Let’s discuss them one by one.

  • post_type: Post type name like the post, page, attachment, revision, etc;
  • post_status: Post status like publish, draft, pending, etc.
  • posts_per_page: Number of posts needed.
  • orderby: Order post by the date, title, ID, etc.
  • order: ASC , DESC. Ascending or Descending order.

Most used queries in WP_Query

We can also make the query with the below queries.

Refer to their official documents for more details.

Write optimized WP_Query

Here I’m sharing the most awaited things about optimized WP_Query. Here is something you need to know when you write the WP_Query.

  • Always avoid 'posts_per_page' => '-1' in the query. Keep the appropriate number. What if the post count is 50000? That will cause the site performance.
  • Use 'no_found_rows' => true when you are not using pagination. That will not run the extra database query to get the post count and the number of pages for pagination.
  • Use 'fields' => 'ids' when you need only the post ID.
  • Use 'update_post_meta_cache' => false, when you don’t require the meta.
  • Use 'update_post_term_cache' => false, when the taxonomy term is not used.

So let’s see again a small example:

<?php
// WP_Query

$args = [
	'post_type'              => 'post',
    'post_status'            => 'publish',
    'posts_per_page'         => '5',
    'orderby'                => 'date',
    'order'                  => 'DESC',
    'no_found_rows'          => true,
    'update_post_meta_cache' => false,
    'update_post_term_cache' => false,
    'fields'                 => 'ids',
];

$query = new WP_Query( $args );

if ( $query->have_posts() ) :

	while ( $query->have_posts() ) : $query->the_post();
	?>
		<div class="posts-wrap">
			<h2><?php the_title(); ?></h2>
		</div>
	<?php
	endwhile;

	wp_reset_postdata();

else:
	// No any post found!
endif;
?>

So this way you can write an optimized WP_Query. That will give you a better performance.

Avoid post__not_in

We use post__not_in for not including that post in a query. We probably use this functionality on the article page. So when we show a recent post or some particular posts then we can exclude the current post from it.

If we use post__not_in in our query then every time that query will leverage a unique cache for all posts and that will affect site performance. So instead of that we can check that thing in a loop and can filter the not needed posts. See the below example.

$args = array(
    'post_type'      => 'page',
    'post_status'    => 'publish',
    'posts_per_page' => 5 + count( $exclude_posts ), // $exclude_posts is an array of post IDs
    'no_found_rows'  => true,
);
$query = new WP_Query( $args );

while ( $query->have_posts() ) {
    $query->the_post();
    $current_post = get_the_ID();
    if ( in_array( $current_post, $exclude_posts ) ) {
        continue;
    }
    the_title( '<h2><a href="' . get_permalink() . '">', '</a></h2>');
}

wp_reset_postdata();

Hope you like the article!

Must Read:

How to contribute to a WordPress core?

Share this:

Related Post

How to contribute to a WordPress core in 2025?

How to contribute to a WordPress core in 2025?

Create a custom REST endpoint in WordPress[1 example]

Create a custom REST endpoint in WordPress[1 example]

How to create a custom shortcode in WordPress

How to create a custom shortcode in WordPress

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.