TransWikia.com

Exclude category from shortcode

WordPress Development Asked by sot on February 26, 2021

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?

2 Answers

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);

Correct answer by Tunji on February 26, 2021

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);

Answered by iguanarama on February 26, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP