Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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

This comment has been minimized.

Copy link

@felipeelia felipeelia commented Apr 28, 2018

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

This comment has been minimized.

Copy link

@Somberor 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

This comment has been minimized.

Copy link

@abulooz 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

This comment has been minimized.

Copy link

@JeffNicholls97 JeffNicholls97 commented Jun 24, 2020

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

@abulooz

This comment has been minimized.

Copy link

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

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.