WordPress: Faster WP_Query with preselected fields

WordPress: Faster WP_Query with preselected fields

Table of contents

I had already written something about it on my website, but since I find this little "trick" very useful and it has helped me from many "slow" rides, I share it here today.

In WordPress you can create your own queries using the class WP_Query(). The problem with these queries is that if they are used frequently, they are very slow, because WordPress loads all fields of the database there.

To explicitly get IDs, you can put the following into the arguments of the query, so that only IDs are loaded:

$args = [
  'post_type' => 'my-post-type',
  'posts_per_page' => -1,
  'fields' => 'ids', // select IDs only
];

$query = new WP_Query( $args );

print_r( $query->posts );
// [ 1, 2, 3, 4, 5 ]

Here only the IDs are loaded. This saves a lot of time, even if it looks like more effort. This method is also very helpful if you want to combine several queries.

Remember that if you use get_the_title() or similar functions, WordPress will automatically load the entire post with get_post() again. Instead, you can load the full query again and save yourself the extra effort. You can also use get_post() only once in the loop and then retrieve the content:

$args = [
  'post_type' => 'my-post-type',
  'posts_per_page' => -1,
  'fields' => 'ids', // select IDs only
];

$query = new WP_Query( $args );

if( $query->found_posts ):
  foreach( $query->posts as $post_id ):
    $post = get_post($post_id);
    print $post->post_title;
  endforeach;
endif;

How do you build your queries?

Did you find this article valuable?

Support Kevin Pliester by becoming a sponsor. Any amount is appreciated!