Return only Count from a wp_query request?

Is it possible with the standard build-in tools in WordPress to get wp_query to only return the count of an query?

Right now, I’ve a query which has several meta_queries but what the only thing I’m interested in is the actually count of the query.

I know that I can use the found_posts property but the query itself generates a big overhead by query SELECT * and thus returns the whole object.

I could just as easy query the DB with a custom query using $wpdb but I would like to utilize the build-in query system if possible..

I’ve been looking for the answer for this on SE and Google but came on empty.

If I’ve explained myself poorly, please let me know and I’ll try to elaborate.

Cheers

3 s
3

There is no build in function to achieve what you want, at least not for complicated meta queries like this. If you need to use build in functions for this, the best will be to make use of WP_Query.

To make the query faster and to skip the unwanted returned array of WP_Post properties, and because you are only interested in post count, you can use the following in your parameters in your arguments

'fields' => 'ids',
'no_found_rows' => true,

This might even be a bit faster than a custom SQL query, and the results from WP_Query is cached as well.

Leave a Comment