Display cart item count in Woocommerce cart widget

时光毁灭记忆、已成空白 提交于 2019-12-02 03:25:23

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

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