0

I know I can use something like this to count for ONE tax:

$catcount=get_term_by('slug','apple', 'FRUIT');
echo $catcount->count;

but not sure how to count posts that are in combos between taxonomies...

I have two custom taxonomies, and I want to count the number of posts (custom post types, actually) that are in each pair match between them. So for example:

TAXONOMY ONE:

  • rock
  • paper
  • scissors

TAXONOMY FRUIT:

  • apple
  • banana
  • strawberry

And I want to query the taxonomies and return results for a count of:

  • number of posts that are in rock and apple
  • number of posts that are in rock and banana
  • number of posts that are in rock and strawberry
  • number of posts that are in paper and apple
  • number of posts that are in paper and banana
  • number of posts that are in paper and strawberry
  • number of posts that are in scissors and apple
  • number of posts that are in scissors and banana
  • number of posts that are in scissors and strawberry

Is this something I need to use SQL for, or is there a good WP way to get at these counts?

1

Here is how I ended up solving it, with some thanks to Samuel for pointing at tax_query, although that was only part of the picture. I needed to create a loop, and I did it like so:

$ones = get_terms( array(
    'taxonomy' => 'ONE',
    'hide_empty' => false,
    'fields' => 'id=>slug' 
) );

$fruits = get_terms( array(
    'taxonomy' => 'FRUIT',
    'hide_empty' => false,
    'fields' => 'id=>slug' 
) );


foreach ($fruits as $fruit) {

foreach ($ones as $one) {

$args = array(
    'post_type' => 'my-post-type',
 'post_status'=>'publish',
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'ONE',
            'field'    => 'slug',
            'terms'    => array( $one ),
        ),
        array(
            'taxonomy' => 'FRUIT',
            'field'    => 'slug',
            'terms'    => array( $fruit ),
        ),
    ),
);
$query = new WP_Query( $args );

echo $fruit .": " . $one . ": " . $query->post_count . "<br>";

}
}
  • Just to note that this will scale badly as the number of terms in each taxonomy grows. If this needs to be displayed on each page load, it may be better to cache the results in a transient and load the data from that on each subsequent page load. You would need to clear / rebuild the transient each time you add/remove a term, or assign/remove a term from a post. – Alexander Holsgrove Feb 3 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.