0

I would like to create a custom shortcode that count individually product-categories in Woocomerce but I haven't found any code on net. I need somethink like:

[counter product-category="example"]

Anyone can help me? I've no idea about php :(

<?php
$product_categories = get_terms( 'product_cat', $args );
$count = count($product_categories);
?> 
  • what do you want ? the numbers of products in a category ? or the number of categories with products ? – mmm Apr 15 '18 at 19:19
  • The total products in a category. – PhineasD Apr 15 '18 at 19:26
  • you can retrive the category object with the function get_term and then you can have the product count in the argument count of the object. – mmm Apr 15 '18 at 19:38
0

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

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.