How to display a WooCommerce shopping cart in the site header

To display the shopping cart button displaying the number of products in the site header, add some code to the theme file header.php, which is responsible for output of the header:

<div class="s-header__basket-wr woocommerce">
    <?php global $woocommerce; ?>
    <a href="<?php echo $woocommerce->cart->get_cart_url() ?>" class="basket-btn basket-btn_fixed-xs">
        <span class="basket-btn__label">Cart</span>
        <span class="basket-btn__counter">(<?php echo sprintf($woocommerce->cart->cart_contents_count); ?>)</span>
    </a>
</div>

To update the number of products immediately after adding the product to the cart without reloading the page, add the following code to functions.php:

add_filter('woocommerce_add_to_cart_fragments', 'header_add_to_cart_fragment');

function header_add_to_cart_fragment( $fragments ) {
    global $woocommerce;
    ob_start();
    ?>
    <span class="basket-btn__counter">(<?php echo sprintf($woocommerce->cart->cart_contents_count); ?>)</span>
    <?php
    $fragments['.basket-btn__counter'] = ob_get_clean();
    return $fragments;
}

Now we style the button:

download an icon

.basket-btn {
    display: inline-block;
    max-width: 100%;
    background-color: #77787b;
    font-family: sans-serif;
    font-size: 16px;
    color: white;
    font-weight: bold;
    background-repeat: no-repeat;
    background-position: 9px center;
    background-size: 25px 25px;
    background-image: url(ico-basket.png);
    border-radius: 20px;
    padding-left: 43px;
    padding-top: 12px;
    padding-bottom: 12px;
    padding-right: 19px;
}

Updated: 18.04.2020

Did this article help you? Rate it!
(No Ratings Yet)
Loading...

Support on Patreon https://www.patreon.com/processby

Leave a Reply

Your email address will not be published. Required fields are marked *

Contacts

E-mail: processby@gmail.com
Skype: inprocess.by
Belarus, Grodno

Send message