7

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

  • Maybe something like this answer where I extend the WP_Query class to return only the count? – birgire Feb 12 '15 at 10:34
  • @birgire I totally forgot about your post there. I even upvoted it some stage. :-). Definitely a way to go here – Pieter Goosen Feb 12 '15 at 10:38
  • thanks, I had forgotten about this myself, until now ;-) @PieterGoosen – birgire Feb 12 '15 at 10:42
9

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.

  • Thanks.. and yes of cause it will benefit to use the fields argument for this solution.. It dramatically increased the performance :-) – Mestika Feb 12 '15 at 10:54
  • My pleasure, glad I could help :-) Enjoy – Pieter Goosen Feb 12 '15 at 10:57
0

I know this has been answered and since your question was based off on using WP_Query, my answer is probably a long-shot but you could also try to use this:

wp_count_posts( $type, $perm );

where $type = post_type (post, page, 'custom-post-type-slug') and where $perm = To include private posts readable by the current user, set to 'readable'

I've used this in the past with great success :)

wp_count_posts('post')->publish -> returns only the count for published posts.
  • This works yes, but it counts all posts within a given post type within a given status. The problem is, this does not work for custom fields :-) – Pieter Goosen Feb 16 '15 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.