Fastest way of counting posts of a custom post type in a specific taxonomy term?
I know this kind of question is legion but I have read through all related topics and I can't find a satisfying solution.
What I want to achieve is simple: on my taxonomy (author) term archive page I have a list of all terms within that taxonomy from which you can select to switch from one term to another.
I want to display the number of posts only from the post type (several CPT are associated with author).
Simply put I want it to look like this:
ul
li class=cat-itema href=example.com/author/albert-camusAlbert Camus/a (233)/li
li class=cat-itema href=example.com/author/jean-fontaineJean de la Fontaine/a (134)/li
li class=cat-itema href=example.com/author/victor-hugoVictor Hugo/a (82)/li
/ul
But I have hundreds of authors and thousands of posts.
Wether I use get_posts
or WP_query
the page takes forever to load. I understand why. Because it makes hundreds of request to count the number of posts.
Most of the topics on this subject in here use this kind of solution to do that :
$the_query = new WP_Query( array(
'post_type' = 'post',
'tax_query' = array(
array(
'taxonomy' = $taxonomy,
'field' = 'term_id',
'terms' = $term-term_id
)
)
) );
$count = $the_query-found_posts;
If I do that within the loop to list all terms, it destroys my server.
Is there a way to easily count the number of posts from a specific cpt inside a term that is more performance proof?