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' );
    //var_dump($resul);
    
    if ( false === $result ) {
        
        $args = array(
        'post_type'       => $posttype,
        'post_status'     => 'publish',
        'posts_per_page'  => -1,
        'tax_query' => array(
          'relation' => 'AND',
          array(
            'taxonomy'  => $taxname,
            'field'     => 'id',
            'terms'     => array( $id )
          )
        )
      );



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

      $cacheresult = wp_cache_set( 'taxpostcount'.$id, $result, 'cbtaxpostcount' );
      //var_dump($cacheresult);
    } 
    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 *