Shortcode with product catgory counter

Try this: (add it to the theme’s main functions.php file)

add_shortcode( 'products-counter', 'products_counter' );
function products_counter( $atts ) {
    $atts = shortcode_atts( [
        'category' => '',
    ], $atts );

    $taxonomy = 'product_cat';
    if ( is_numeric( $atts['category'] ) ) {
        $cat = get_term( $atts['category'], $taxonomy );
    } else {
        $cat = get_term_by( 'slug', $atts['category'], $taxonomy );
    }

    if ( $cat && ! is_wp_error( $cat ) ) {
        return $cat->count;
    }
    return '';
}

You can use it like this:

  • By specifying the product category ID:

[products-counter category="19"]

  • By specifying the product category slug:

[products-counter category="hoodies"]

Example:

enter image description here

Leave a Comment