Custom cart item counts by product category in Woocommerce 3

▼魔方 西西 提交于 2019-12-07 17:17:28

The main problem comes from the refreshed woocommerce ajax cart fragments that use by default "cart-contents" class and the existing content with the refreshed default cart count.

So we will need to:

  • rename that class differently,
  • add the content (to be refreshed on add to cart) in a specific hooked function.

I have also revisited, simplified and compacted your function cat_cart_count().

The complete code:

// Utility function that count specific product category cart items
function cat_cart_count( $term ) {
    $count = 0; // Initializing

    // Loop through cart items
    foreach( WC()->cart->get_cart() as $cart_item ) {
        if( has_term( $term, 'product_cat', $cart_item['product_id'] ) )
            $count += $cart_item['quantity'];
    }
    // Returning category count
    return $count == 0 ? false : $count;
}

// Utility function that displays the cart items counters
function display_cart_counters() {
    ob_start();

    $link  = wc_get_cart_url();
    $title = __( 'View your shopping cart', 'woocommerce' );
    $count = __( '0 item', 'woocommerce');

    // Displayed on first page load
    echo '<a class="cart-contents-cat" href="' . $link . '" title="' . $title . '">' . $count . '</a>';

    return ob_get_clean();
}

// Displaying refreshed content on add-to cart
add_filter( 'woocommerce_add_to_cart_fragments', 'counters_add_to_cart_fragment', 30, 1 );
function counters_add_to_cart_fragment( $fragments ) {
    ob_start();

    $term1   = 'protein';
    $count1  = cat_cart_count( $term1 );
    $output  = $count1 ? sprintf ( __( '%d %s', 'woocommerce'), $count1, $term1 ) . ' - ' : '';

    $term2   = 'pantry';
    $count2  = cat_cart_count( $term2 );
    $output .= $count2 ? sprintf ( __( '%d %s', 'woocommerce'), $count2, $term2 ) . ' - ' : '';

    $count   = WC()->cart->get_cart_contents_count();
    $output .= $count ? sprintf (_n( '(%d item)', '(%d items)', $count ), $count ) : __( '0 item', 'woocommerce');

    $link    = wc_get_cart_url();
    $title   = __( 'View your shopping cart', 'woocommerce' );

    // Replacement display on any cart item events
    ?>
    <a class="cart-contents-cat" href="<?php echo $link; ?>" title="<?php echo $title ?>"><?php echo $output; ?></a>
    <?php
    $fragments['a.cart-contents-cat'] = ob_get_clean();

    return $fragments;
}

Code goes in function.php file of your active child theme (or active theme).Tested and works.


USAGE

1) To place the counter in the html code of a php file you will use:

<?php echo display_cart_counters(); ?>

2) To use the counter inside any php code you will call the function **display_cart_counters()**.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!