Display cart item count in Woocommerce cart widget

后端 未结 2 1911
小蘑菇
小蘑菇 2021-01-24 12:41

I am trying to display the count of the items in the cart at the bottom or top of the Woocommerce cart widget. It seems that by default behaviour the cart widget does not do thi

相关标签:
2条回答
  • 2021-01-24 13:11

    If you want to display the cart item count in the mini cart widget you can use hooks:

    1) On top before minicart content:

    add_action( 'woocommerce_before_mini_cart', 'minicart_count_after_content' );
    function minicart_count_after_content() {
        $items_count = WC()->cart->get_cart_contents_count();
        $text_label  = _n( 'Item', 'Items', $items_count, 'woocommerce' );
        ?>
            <p class="total item-count"><strong><?php echo $text_label; ?>:</strong> <?php echo $items_count; ?></p>
        <?php
    }
    

    2) On the bottom before the buttons:

    add_action( 'woocommerce_widget_shopping_cart_before_buttons', 'minicart_count_before_content' );
    function minicart_count_before_content() {
        $items_count = WC()->cart->get_cart_contents_count();
        $text_label  = _n( 'Item', 'Items', $items_count, 'woocommerce' );
        ?>
            <p class="total item-count"><strong><?php echo $text_label; ?>:</strong> <?php echo $items_count; ?></p>
        <?php
    }
    

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


    WC()->cart->get_cart_contents_count(); will give you the total items count including quantities.

    If you want to get the number of items in cart you will use instead:

    $items_count = sizeof( WC()->cart->get_cart() );
    
    0 讨论(0)
  • 2021-01-24 13:22

    You aren't echoing WC()->cart->get_cart_contents_count() anywhere, so no, it won't display.

    Wherever in the code you need to display the count, you'll need to use

    echo WC()->cart->get_cart_contents_count();
    
    0 讨论(0)
提交回复
热议问题