Here is a way to add the WooCommerce cart icon to the header with the cart count. This solution is quite simple and can be added to any theme, just follow these steps and you will have a cart icon in your theme header.
Step 1:
Add the code to the theme’s template file header.php
where you want your cart icon to be. Ensure WooCommerce is active for the icon to appear. Ecommerce Web Design Mississauga experts recommend following these steps to seamlessly integrate the cart icon into your WooCommerce website.
<?php
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
$count = WC()->cart->cart_contents_count;
?>
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">
<?php if ( $count > 0 ) { ?>
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php } ?>
</a>
<?
php } // if (in_array)
?>
Step 2:
Add the following to your functions.php
to ensure that the cart is simultaneously updated as items are added to the cart.
/*
* Add Cart in header
*/
function my_header_add_to_cart_fragment( $fragments ) {
ob_start();
$count = WC()->cart->cart_contents_count;
?>
<a class="cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>">
<?php if ( $count > 0 ) { ?>
<span class="cart-contents-count"><?php echo esc_html( $count ); ?></span>
<?php } ?>
</a>
<?php
$fragments['a.cart-contents'] = ob_get_clean();
return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'my_header_add_to_cart_fragment' );
Step 3:
/* cart css */
.cart-contents:before {
font-family: WooCommerce;
content: “\e01d”;
font-size: 28px;
margin-top: 10px;
font-style: normal;
font-weight: 400;
padding-right: 5px;
vertical-align: bottom;
color: #fff;
}
.cart-contents:hover {
text-decoration: none;
}
.cart-contents-count {
color: #fff;
background-color: #2ecc71;
font-weight: bold;
border-radius: 10px;
padding: 1px 6px;
line-height: 1;
font-family: Arial, Helvetica, sans-serif;
vertical-align: top;
}
Now, you have added the cart item as well as count to your WooCommerce website. Add items to the cart to see your work in action. Work on your WooCommerce project and build an e-commerce store that your client needs. High-quality expert web design in Mississauga who are up-to-date with the latest developments, resulting in efficient, robust, and intuitive plugins.