$term_items = array
();
$terms_by_id = array
();
$term_ids = array
();
foreach ( (array) $terms as $key =>
$term ) { $terms_by_id[ $term->term_id
] = &
$terms[ $key ];
$term_ids[ $term->term_taxonomy_id
] =
$term->term_id;
} // Get the object and term IDs and stick them in a lookup table.
$tax_obj =
get_taxonomy( $taxonomy );
$object_types =
esc_sql( $tax_obj->object_type
);
$results =
$wpdb->
get_results( "SELECT object_id, term_taxonomy_id FROM
$wpdb->term_relationships INNER JOIN
$wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" .
implode( ',',
array_keys( $term_ids ) ) . ") AND post_type IN ('" .
implode( "', '",
$object_types ) . "') AND post_status = 'publish'"
);
foreach ( $results as $row ) { $id =
$term_ids[ $row->term_taxonomy_id
];
$term_items[ $id ][ $row->object_id
] =
isset( $term_items[ $id ][ $row->object_id
] ) ? ++
$term_items[ $id ][ $row->object_id
] : 1;
} // Touch every ancestor's lookup row for each post in each term.
foreach ( $term_ids as $term_id ) { $child =
$term_id;