11

Is there a way to count all published posts from a custom taxonomy?

While looking around I found this snippet but I didn’t manage to get it to work …

global $wpdb;
$query = "
        SELECT COUNT( DISTINCT cat_posts.ID ) AS post_count
        FROM wp_term_taxonomy AS cat_term_taxonomy INNER JOIN wp_terms AS cat_terms ON
        cat_term_taxonomy.term_id = cat_terms.term_id
        INNER JOIN wp_term_relationships AS cat_term_relationships 
        ON cat_term_taxonomy.term_taxonomy_id = cat_term_relationships.term_taxonomy_id
        INNER JOIN wp_posts AS cat_posts 
        ON cat_term_relationships.object_id = cat_posts.ID
        WHERE cat_posts.post_status = 'publish' 
        AND cat_posts.post_type = 'post' 
        AND cat_term_taxonomy.taxonomy = 'YOUR-CUSTOM-TAXONOMY' 
        AND cat_terms.slug IN ('TERM-SLUG-1, TERM-SLUG-2')
    ";
return $wpdb->get_var($query);

10 Answers 10

9

Use an instance of WP_Query to query the database. http://codex.wordpress.org/Class_Reference/WP_Query

To query database for custom taxonomies use,

$query = new WP_Query( array( 'people' => 'bob' ) );

For more details on available options see: Taxonomy Parameters http://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

Retrieve published posts using

'post_status' => 'publish'

Use found_posts to retrive the number of posts

$count = $query->found_posts;
2
  • Don't forget to wp_reset_postdata(). Commented Mar 20, 2021 at 12:08
  • @amarinediary in this case you actually dont have to reset the post data. You only need to do this if you loop the posts and use $query->the_post(); which will overwrite the loop's global $post object. If you are just getting counts, resetting the post data is just extra compute.
    – noahmason
    Commented Feb 28, 2023 at 19:34
8
function wp_get_productcat_postcount($id) {

    //return $count;
    $args = array(
      'post_type'     => 'product', //post type, I used 'product'
      'post_status'   => 'publish', // just tried to find all published post
      'posts_per_page' => -1,  //show all
      'tax_query' => array(
        'relation' => 'AND',
        array(
          'taxonomy' => 'product_cat',  //taxonomy name  here, I used 'product_cat'
          'field' => 'id',
          'terms' => array( $id )
        )
      )
    );

    $query = new WP_Query( $args);

    /*
    echo '<pre>';

    print_r($query->post_count);
    echo '</pre>';
    */

    return (int)$query->post_count;

}
5

I really like the simplicity of Varsha Dhadge's answer, but that is for taxonomy terms attached to one post in particular. For the entire site, use get_terms in a similar way instead:

$custom_cats = get_terms(
    'custom_cat', // your custom taxonomy slug
    array(
        // get all the terms, even empty ones so we can see what items have 0
        'hide_empty' => false,
    )
);

foreach ( $custom_cats as $term ) {
    echo $term->slug . ' - ' . $term->count . '<br>';
}
3

Below code will get count of article from particular taxonomy

<?php 
  $terms = get_the_terms( $post->ID , 'your-taxonomy' );
  foreach ( $terms as $term ) {
    echo $term->count;
  } ?>
2
  • this gets only the terms that are attached to $post->ID. see my solution using get_terms instead. Commented Jul 14, 2020 at 1:01
  • Note that $term->count still does give you the total count of posts using that term on the whole site - but you will only get terms attached to the current post. Maybe that's what some people are looking for here, but if you want all the terms on the whole site - which is the OP question - you need get_terms. Commented Jul 14, 2020 at 1:07
2

You can do this with the current object with get_queried_object()

$posts = get_queried_object();
echo $posts->count;

Otherwise you may unnecessarily run a second query, right?

1
  • Brilliant! :) Thanks a lot. This works for when I'm inside a category. :)
    – Woppi
    Commented May 31, 2017 at 9:50
0

Wordpress adds attribute count to each taxonomy and updates it whenever a new post is inserted or updated. Because it does not want to go to database again and do calculations to get posts count in taxonomy.

echo $custom_tax_obj->count;
0
0

I face this situation in the taxonomy archive templates (e.g. taxonomy-taxname.php) for a site with a custom post type and associated category/tag taxonomies. I wanted in my header to display a count of how many items used the taxonomy.

In my taxonomy archive templates, I needed to find the term the taxonomy represented, then pass it off to a function to get the number of custom post type items using that term, this from the tag taxonomy

// the term we need for this taxonomy
$term_obj = get_queried_object(); 

// get the term object
$term = get_term( $term_obj->term_id, 'taxname' );

// get a count of content with this term
$tax_count = get_tax_count('taxname', $term->slug, 'custom-post-type-name');

// grammar counts
$plural = ( $tax_count == 1) ? '' : 's';

echo $tax_count . ' Item' . $plural . ' Tagged "' . $term->name . '"';

The function for doing the count uses WP_Query with a tax_query:

function tax_count ( $taxonomy, $term, $post_type ) {
    // find the number of items in custom post type that use the term in a taxonomy

    $args = array(
        'post_type' =>  $post_type,
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => $taxonomy,
                'field'    => 'slug',
                'terms'    => $term,
            ),
        ),
    );

    $tax_query = new WP_Query( $args );

    return ($tax_query->found_posts);

}
-1
$args = array(
'post_type' => 'product',
'post_status' => 'published',
'product_cat' => $catpage, // $catpage == your category slug name
'numberposts' => -1
);
echo $num = count( get_posts( $args ) );
1
  • Please take a minute and explain what your code is doing.
    – user9447
    Commented Aug 24, 2016 at 13:46
-1

I have created this function for my requirement and exactly match this question.

Get Post Count In or Not In Taxonomy

/**
 * Get Post/Post Type Count in the given Taxonomy
 *
 * @param  $post_type string any post type
 * @param  $taxonomy string any taxonomy
 * @param  $is_exists string NOT EXISTS or EXISTS
 *
 * @return String Number of Post count
 */

function prefix_get_post_count_in_taxonomy($post_type, $taxonomy, $is_exists = 'NOT EXISTS')
{
    global $wpdb;

    $count = $wpdb->get_var(
        "
select COUNT(*) as post_count  
    FROM $wpdb->posts as A 
WHERE $is_exists (
    SELECT 1
    FROM 
         $wpdb->term_relationships as B
             INNER JOIN $wpdb->term_taxonomy as C
                 ON C.term_taxonomy_id = B.term_taxonomy_id
    WHERE C.taxonomy = '$taxonomy'
      AND B.object_id = A.ID
    )                                                    
  AND A.post_type = '$post_type'
  "
    );

    return $count;
}


/**
 * Example
 *
 * Post type: download
 * Taxonomy: download_category
 * Is Exist: EXISTS
 */
echo prefix_get_post_count_in_taxonomy('download', 'download_category', 'EXISTS');
-1

This method i have followed and it worked for me.

 $terms = get_terms([
    'taxonomy' => 'types',
    'hide_empty' => false,
]);
$taxonomies = [];

foreach($terms as $term){
    echo $term->name .'----->'.$term->count.'<br>';  //here it gives post counts.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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