Enable AJAX add to cart buttons on archives

want to add update cart with ajax but doesnt work. Using code from woocommerce:

Settings->Product->Display->Enable AJAX add to cart buttons on archives

header.php
<a class="cart-customlocation" href="<?php echo wc_get_cart_url(); ?>" title="<?php _e( 'View your shopping cart' ); ?>"><?php echo sprintf ( _n( '%d item', '%d items', WC()->cart->get_cart_contents_count() ), WC()->cart->get_cart_contents_count() ); ?> - <?php echo WC()->cart->get_cart_total(); ?></a>

extras.php
add_filter('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 $woocommerce->cart->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;

}

Adding to cart is working but I need to refresh the page. Does sage need some jquery to add?

1 Like

extras.php is a namespaced file. You need to call the namespace when calling your function:

add_filter('add_to_cart_fragments', __NAMESPACE__ . '\\woocommerce_header_add_to_cart_fragment');

If you turn on php errors, you’ll get notices about items such as these.

2 Likes

thanks! solved!

add_filter('add_to_cart_fragments', __NAMESPACE__ . '\\woocommerce_header_add_to_cart_fragment');

function woocommerce_header_add_to_cart_fragment( $fragments ) 
    {
        global $woocommerce;
    ob_start(); ?>

<a class="cart-contents" href="<?php echo $woocommerce->cart->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-contents'] = ob_get_clean();
return $fragments;

}

1 Like