Crerem
Crerem

Reputation: 1359

Get no of posts inside with a term for a custom taxonomy

How can i get the no of posts inside a term of a custom taxonomy ? (including the posts that are attached to a child term).

For example i have:

Right now i'm, doing it like this:

$categories = get_terms($taxonomy,$args);
foreach ($categories as $categ) {
    print $categ->name.' / '.$categ->count;
}

But for "term" i get only 2 posts when i really need to show 5( 2 from "term" and 3 from it's children).

Thanks

Upvotes: 0

Views: 2132

Answers (2)

rnevius
rnevius

Reputation: 27102

There is an easier way to do this: do a standard WP_Query with taxonomy parameters:

$args = array(
    'post_type' => 'post',
    'tax_query' => array(
        array(
            'taxonomy' => 'your_custom_taxonomy',
            'field'    => 'slug',
            'terms'    => 'your-parent-term-name',
        ),
    ),
);
$query = new WP_Query( $args );

// Get the count
$count = $query->post_count;

If you don't know the name(s) of terms within a taxonomy, you can do a query and pass their IDs as an array to WP_Query. See this post on WPSE for more info.

Upvotes: 3

vard
vard

Reputation: 4136

This is something I run into few times, and I changed the code from PatchRanger on bountify to make it work with taxonomies (so please note this solution is based on his work):

function wp_get_term_postcount($term) {
    $count = (int) $term->count;
    $tax_terms = get_terms($term->taxonomy, array('child_of' => $term->term_id));
    foreach ($tax_terms as $tax_term) {
        $count += wp_get_term_postcount_recursive($tax_term->term_id);
    }
    return $count;
}

function wp_get_term_postcount_recursive($term_id, $excludes = array()) {
    $count = 0;
    foreach ($tax_terms as $tax_term) {
        $tax_term_terms = get_terms($tax_term->name, array(
            'child_of' => $tax_term->term_id,
            'exclude' => $excludes,
        ));
        $count += $tax_term->count;
        $excludes[] = $tax_term->term_id;
        $count += wp_get_term_postcount_recursive($tax_term->term_id, $excludes);
    }
    return $count;
}

The recursive function is there to prevent double counting of childs. You can add those two functions inside functions.php.

Then update your code to use it:

$categories =  get_terms($taxonomy, $args);
foreach($categories as $categ) {
    print  $categ->name.' / 'wp_get_term_postcount($categ);
}

Upvotes: 0

Related Questions