How do I count the number of taxonomy terms which have both a) an associated post and b) where that post also has an associated term from another taxonomy?
Specifically, I have...
article
" (9,000+ posts)format
" (11 terms)company
" (1,624 terms)An article is taggable with both a "format
" and a "company
".
I want to get a count of the number of "companies" about which there is an "article
" with the "format
" term "viewpoint
" or, more importantly, any of its 3 children. How can I do this?
Ordinarily, I think the question would be "How do I count the number of 'articles
' tagged with any 'company
'"? Except that I would like specifically those qualifying articles to be of the "format
" taxonomy's "viewpoint
" term or one of its children.
Am I thinking of this backward? Is this about asking: "Find all 'articles
' tagged with both any 'company
' and 'format
' of 'viewpoint
', and then return a count of those 'articles
'"?
I think I should avoid a WP_Query
as we are talking about a large number of items here, especially for "article
". What is an efficient way?
I feel like get_object_term
coupled with children may be useful here?
The following code does something different (counts the number of objects with "viewpoint
" or a child alone. But maybe it's a start...
// Get Viewpoints total count
$term = get_term_by('slug', 'viewpoint', 'format');
$id = $term->term_id;
$count = 0;
$taxonomy = 'format';
$args = array('child_of' => $id);
$tax_terms = get_terms($taxonomy,$args);
foreach ($tax_terms as $tax_term) {
if ($tax_term->parent == $id) {
$count +=$tax_term->count;
}
}