admin管理员组

文章数量:1321260

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

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);
?> 
Share Improve this question asked Apr 15, 2018 at 19:09 PhineasDPhineasD 351 silver badge4 bronze badges 3
  • what do you want ? the numbers of products in a category ? or the number of categories with products ? – mmm Commented Apr 15, 2018 at 19:19
  • The total products in a category. – PhineasD Commented Apr 15, 2018 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 Commented Apr 15, 2018 at 19:38
Add a comment  | 

1 Answer 1

Reset to default 1

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:

本文标签: woocommerce offtopicShortcode with product catgory counter