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?
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?
Share Improve this question edited Dec 30, 2016 at 17:50 Tunji 2,9611 gold badge18 silver badges28 bronze badges asked Dec 29, 2016 at 22:36 sotsot 451 silver badge9 bronze badges 8 | Show 3 more comments2 Answers
Reset to default 1I 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);
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);
'category__not_in' => 6
parameter – Tunji Commented Dec 30, 2016 at 4:56get_term
so as to accommodate custom taxonomies – Tunji Commented Dec 30, 2016 at 16:50