Category Post Count in WordPress (Custom Taxonomy with Custom Post Type)

Let me explain my need in short:

I want to show post count for any category/any custom taxonomy registered for any custom post type. I searched wordpress forums and in google, found some solutions using

Nothing helped me such way, so I managed my own way with my little knowledge.

wp_get_productcat_postcount($id, $posttype = ‘product’, $taxname = ‘product_cat’)

$id = category or any taxonomy id(term id)
$posttype = post type name, example: post, page, or any custom post type
$taxname = taxonomy name or any category type name, for joomla default taxonomy it will category, post_tag, nav_menu, link_category, post_format, but we can use any custom taxonomy name as I used ‘product_cat’ which is used with custom post type ‘product’ , post type name.

function wp_get_productcat_postcount($id, $posttype = 'product', $taxname = 'product_cat') {
    $result = wp_cache_get( 'taxpostcount'.$id, 'cbtaxpostcount' );
    if ( false === $result ) {
        $args = array(
        'post_type'       => $posttype,
        'post_status'     => 'publish',
        'posts_per_page'  => -1,
        'tax_query' => array(
          'relation' => 'AND',
            'taxonomy'  => $taxname,
            'field'     => 'id',
            'terms'     => array( $id )

      $query = new WP_Query( $args);
      echo '<pre>';
      echo '</pre>';
      $result = (int)$query->post_count;

      $cacheresult = wp_cache_set( 'taxpostcount'.$id, $result, 'cbtaxpostcount' );
    return $result;        

Note: As I used wordpress object cache for better performance.

Thanks for reading, any comment is appreciable.

Leave a Reply

Your email address will not be published. Required fields are marked *