0

I have the following code and i am trying to exclude a specific category id ex-144

function product_count_shortcode( ) {
    $count_posts = wp_count_posts( 'product' );
    return $count_posts->publish;
}
add_shortcode( 'product_count', 'product_count_shortcode' );

How can exclude one category?

8
  • You can achieve this using the 'category__not_in' => 6 parameter
    – Tunji
    Commented Dec 30, 2016 at 4:56
  • i try it and doesn't work
    – sot
    Commented Dec 30, 2016 at 16:33
  • You're trying to count posts excluding one category?
    – Tunji
    Commented Dec 30, 2016 at 16:34
  • Yeap that's right!
    – sot
    Commented Dec 30, 2016 at 16:37
  • Updated the code to use get_term so as to accommodate custom taxonomies
    – Tunji
    Commented Dec 30, 2016 at 16:50

2 Answers 2

1

I don't know of a direct method to achieve this, you should be able to get the category count using get_term then subtract that from the total.

function product_count_shortcode( $atts ) {

    $data = shortcode_atts( array(
        'cat_id'    => 144,
        'taxonomy'  => 'category'
    ), $atts );

    $category = get_term( $data['cat_id'], $data['taxonomy'] );
    $count = $category->count;
    $count_posts = wp_count_posts( 'product' );
    return (int)$count_posts->publish - (int)$count;
}
add_shortcode( 'product_count', 'product_count_shortcode' );

From iguanarama answer:

You can also use WP_Query

$myQuery = new WP_Query ([
    'post_type' => 'product',
    'cat' => '-144',
    'post_status' => 'publish'
]);
$count = ($myQuery ? $myQuery->found_posts : 0);
3
  • Updated the code to use get_term so as to accommodate custom taxonomies
    – Tunji
    Commented Dec 30, 2016 at 16:50
  • So i wanna exclude the 144 and 1138 category. The code will be? @tunji-ayoola
    – sot
    Commented Mar 12, 2017 at 1:34
  • 'cat_id' => 144, 1138 ?
    – sot
    Commented Mar 12, 2017 at 1:48
1

You could run a new WP_Query using a '-' for categories to exclude:

$myQuery = new WP_Query ([
    'post_type' => 'product',
    'cat' => '-144',
    'post_status' => 'publish'
]);
$count = ($myQuery ? $myQuery->found_posts : 0);

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.