I have a code, that counts total posts (in certain categories);

$term_slugs = [ 'cat', 'bird', 'chinchilla','dog','ferret','hamster','horse','lizard','mouse','pig','poultry','rabbit','snake','turtle' ];
$terms = get_terms( [
    'taxonomy' => 'post_tag',
    'slug'     => $term_slugs,
] );
/* Or with get_tags():
$terms = get_tags( [ 'slug' => $term_slugs ] );

$post_count = array_sum( wp_list_pluck( $terms, 'count' ) );
echo  $post_count;

Now, I only have one test animal, but what would happened if I for example have 1000, or 10000 ?, will this code take long time to execute? or is there a better way to do this?

Maybe "once a day" run a script and save the result somewhere?, and just fetch the data?

  • 1
    WordPress does a lot of caching in its various get_* functions. get_terms() uses WP_Term_Query::get_terms() which will use cached data if it's available, so that it's not doing a database lookup every time you call get_terms(). But in the end, it's hard to answer this question definitively: it'll depend as well on your hosting situation, among other factors.
    – Pat J
    Feb 29 at 18:01
  • 2
    if a post appears in more than one of those tags you'll have a post count greater than the number of posts on your site, likewise the issue you'll run into first won't probably won't be speed but memory limits. Given that you can use tools such as WP CLI to create thousands of dummy tags this should be testable
    – Tom J Nowell
    Feb 29 at 18:56
  • To address what @TomJNowell points out, you'll want to run an array_unique() before you run your wp_list_pluck() so that will prevent any posts from being counted twice. Feb 29 at 20:58
  • I expect any memory limit error will happen before the array_unique call, most likely inside the get_tags function halfway through fetching the tags. Again though, this is micro-optimisation, until you encounter this issue the only way to get an answer is to test it, different servers and traffic requirements will yield different answers. If it really becomes a problem then you can use an SQL query or increment a separate counter but don't implement that until you can see and measure a slowdown or it's a waste of effort
    – Tom J Nowell
    Mar 1 at 8:53


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.