wp_get_object_terms(): count relative to passed IDs?

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
) );

Leave a Comment

deneme bonusu veren sitelerbahis casinomakrobetceltabetpinbahispolobetpolobet girişpinbahis girişmakrobet girişpulibet girişmobilbahis girişkolaybet giriş