Skip to content

Instantly share code, notes, and snippets.

@woogists
Last active December 31, 2023 10:08
Show Gist options
  • Save woogists/c0a86397015b88f4ca722782a724ff6c to your computer and use it in GitHub Desktop.
Save woogists/c0a86397015b88f4ca722782a724ff6c to your computer and use it in GitHub Desktop.
[Theming Snippets] Show cart contents / total Ajax
/**
* Show cart contents / total Ajax
*/
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );
function woocommerce_header_add_to_cart_fragment( $fragments ) {
global $woocommerce;
ob_start();
?>
<a class="cart-customlocation" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php _e('View your shopping cart', 'woothemes'); ?>"><?php echo sprintf(_n('%d item', '%d items', $woocommerce->cart->cart_contents_count, 'woothemes'), $woocommerce->cart->cart_contents_count);?> - <?php echo $woocommerce->cart->get_cart_total(); ?></a>
<?php
$fragments['a.cart-customlocation'] = ob_get_clean();
return $fragments;
}
@felipeelia
Copy link

I've had to hook it to the proper filter too:
add_filter( 'woocommerce_add_to_cart_fragments', 'woocommerce_header_add_to_cart_fragment' );

@Somberor
Copy link

Somberor commented May 15, 2020

@felipeelia , how to embed it on WP? , I mean how exactly to I make the appear in a certain place on my site?

@abulooz
Copy link

abulooz commented Jun 3, 2020

@felipeelia , how to embed it on WP? , I mean how exactly to I make the appear in a certain place on my site?

login into wordpress admin panel then go to Appearance>>editor in the right side you'll see a full listing of all files, find "Templates" below that search for header.php and add the code in there

@JeffNicholls97
Copy link

is there a way in which you can put this in a shortcode? so that you can place cart count on any page.

@abulooz
Copy link

abulooz commented Jun 25, 2020

@JeffNicholls97

Yes, just add this to you themes function file:
add_shortcode (woocommerce_header_add_to_cart_fragment', 'woocommerce_header_add_to_cart_fragment' );

Then use the short code wherever you want

For example:

add_shortcode ('woo_cart_but', 'woo_cart_but' );
/**

  • Create Shortcode for WooCommerce Cart Menu Item
    */
    function woo_cart_but() {
    ob_start();

     $cart_count = WC()->cart->cart_contents_count; // Set variable for cart item count
     $cart_url = wc_get_cart_url();  // Set Cart URL
    
     ?>
     <li><a class="menu-item cart-contents" href="<?php echo $cart_url; ?>" title="My Basket">
     <?php
     if ( $cart_count > 0 ) {
    ?>
         <span class="cart-contents-count"><?php echo $cart_count; ?></span>
     <?php
     }
     ?>
    

       
<?php

return ob_get_clean();

}

@farshad4-samadi
Copy link

Hello
this code for ajax does not work for me.
i thinks it needs update

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment