skip to Main Content

I have already tried this code:

$cats = get_terms('category');
$counts_by_term = wp_list_pluck( $cats, 'count', 'slug' );
echo $counts_by_term['uncategorized'];

But the problem is that, the category taxonomy is shared to every post type.

Situation:

I have a CPT called Testimonials and enabled the category and created a single post there with uncategorized category.
I also have 5 posts in post post type, all have uncategorized category assigned to them.

Now, I just want to get the number of posts with uncategorized category only from Testimonials post type.

The code above will output: 6

Which should only be: 1

3

Answers


  1. here’s my solutions,

    $cat_id = 1;
    $post_type = 'testimonials'; 
    $args = array(
        'numberposts' => -1,
        'category' => $cat_id,
        'post_type' => $post_type,
    );
    $count_posts = get_posts( $args );
    $total_posts = count($count_posts);
    echo $total_posts;
    
    Login or Signup to reply.
  2. //This would run with less stress to your Database

    $cat_id = 1;
    $args = array(
    'category'=>$cat_id,
    'post_type'=>'testimonials',
    );
    $postTypes = new WP_Query($args);
    $numberOfPosts = $postTypes->found_posts;
    echo $numberOfPosts;
    
    Login or Signup to reply.
  3. $cats = get_terms('category', array('hide_empty' => false,  'show_count' => 1, 'orderby'=>'id', 'order' => 'ASC' )); //in array args put what you want
    
    foreach($cats as $cat):
           echo $cat->count; // return total posts in your custom post type category with  'show_count' => 1, 
    endforeach;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search