I will try to be as explicit and short as possible. Suppose I have a site for books. I have three categories named adventure, romance and fantasy. Then, I have a tag called old books. In the top of this tag archive I need to display some counts information. Example :
OLD BOOKS
There are a total of 88 old books available.
18 books are from adventure category.
50 books are from romance category.
20 books are from fantasy category.
I solved the first one with $wp_query->found_posts;
which gives me the count of total number of books in the tag-archive. Now how do I get the count for rest of the books. A solution or a road map would be great otherwise please tell me what functions or example should I be looking into.
I also expect the count to change dynamically as the changes occur. I will be posting my updates shortly as I am struggling for solution.
I remembered that once I had to do same thing and wrote a custom sql query… it was painful, as @Rarst said.
However I’ll post the function I wrote, and there isn’t much to explain, is a complex SQL query where there is the intersection of 2 checks to get all the term of a specific taxonomy that are associated in post having a specific term in another taxonomy:
As you can see it’s possible to use with different taxonomies and not only tags and categories.
$term
can be a term id or a term slug.Is possible do not to pass any post type as well if the two taxonomies are used by only one custom post type or if one want ot count all post types.
Note that if an invalid CPT is passed it is skipped without return any error.
The function also check if the hook ‘wp_loaded’ was already fired, because before that taxonomies and post types are not registered, so checks for taxonomies or post type existence will fail.
How to use:
Of course replace ‘your_textdomain’ with your real text domain 😉