wp_get_object_terms(): count relative to passed IDs?

I know when you wp_get_object_terms() you get a “count” member variable for each term object returned, but that “count” is what’s in the $wpdb->term_taxonomy table in the database, it’s not relative to the IDs you pass in as the first parameter. How do I get that number, though?

Example, something like:

Read More
$query = new WP_Query(array('post_type' => 'foo', 'numberposts' => 20));
$ids = wp_list_pluck($query->posts, 'ID');
$terms = wp_get_object_terms($ids, 'multi_post_type_tax');

So I want the count returned to be relevant to the query, meaning the count I get is only for the passed in post IDs. Each term object returned from the tax “multi_post_type_tax” may have a count of 400 because it applies to other post types that aren’t in my query, but since I passed in specific IDs, I want that count to apply to that query, meaning a count > 20 wouldn’t make any sense at all (and most likely for a particular term, it’d be less than 20, I can’t see every post in a post type having the same term usually). It seems like that would work but the returned value from wp_get_object_terms has unique objects.

Related posts

1 comment

  1. I’m afraid there won’t be a nice way to do this…

    One way will be to:

    • get all the found posts,
    • for every one of them get its terms,
    • count the terms.

    But it won’t be very efficient and I wouldn’t recommend this way of doing it.

    On the other hand there is an efficient, but not very nice way of doing it – with SQL query:

    $query = new WP_Query(array('post_type' => 'foo', 'numberposts' => 20));
    $ids = wp_list_pluck($query->posts, 'ID');
    
    $placeholders = array_fill(0, count($ids), '%d');
    $format = implode(', ', $placeholders);
    
    $results = $wpdb->get_results( $wpdb->prepare(
        " SELECT terms.name, COUNT(tr.object_id) as count FROM {$wpdb->terms} terms " .
        " INNER JOIN {$wpdb->term_taxonomy} tt ON (tt.term_id = terms.term_id) " .
        " INNER JOIN {$wpdb->term_relationships} tr ON (tr.term_taxonomy_id = tt.term_taxonomy_id) " .
        " WHERE tr.object_id IN ({$format}) GROUP BY terms.term_id ",
        $ids
    ) );
    

Comments are closed.