最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

Get count of terms with a post and another taxonomy term?

matteradmin8PV0评论

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...

  • Custom post type "article" (9,000+ posts)
  • Custom taxonomy "format" (11 terms)
  • Custom taxonomy "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;
    }
  }
Post a comment

comment list (0)

  1. No comments so far