Skip to content

Instantly share code, notes, and snippets.

@gzalinski
Created August 27, 2021 15:41
Show Gist options
  • Save gzalinski/bd5bc115e0d5b2d049325f2c5257b9bf to your computer and use it in GitHub Desktop.
Save gzalinski/bd5bc115e0d5b2d049325f2c5257b9bf to your computer and use it in GitHub Desktop.
Woocommerce Mini Cart with ajax count update
<?php
/**
* @title: WC Mini Cart
* @usage: echo do_shortcode( '[xcminicart]' );
*/
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
new XCMiniCart();
class XCMiniCart {
function __construct() {
add_action('init', [$this,'wp_init']);
}
function wp_init(){
add_filter( 'woocommerce_add_to_cart_fragments', [ $this, 'my_header_add_to_cart_fragment' ] );
add_shortcode( 'xcminicart', [ $this, 'html' ] );
}
function html() {
ob_start();
?>
<div class="mini-cart" id="mini-cart">
<?= $this->html_fragment_cart_icon() ?>
<div class="mini-cart__content">
<?php woocommerce_mini_cart(); ?>
</div>
</div>
<?php
return ob_get_clean();
}
function html_fragment_cart_icon() {
ob_start();
$count = WC()->cart->cart_contents_count;
?>
<a class="mini-cart__button cart-contents" href="<?php echo WC()->cart->get_cart_url(); ?>"
title="<?php _e( 'View your shopping cart' ); ?>">
<span class="button-icon">
<i class="fa fa-shopping-cart" aria-hidden="true"></i>
<?php if ( $count > 0 ) {
echo '<span class="cart-contents-count count">' . $count . '</span>';
} ?>
</span>
</a>
<?php
return ob_get_clean();
}
/**
* Ensure cart contents update when products are added to the cart via AJAX
*/
function my_header_add_to_cart_fragment( $fragments ) {
$fragments['a.cart-contents'] = $this->html_fragment_cart_icon();
return $fragments;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment