Reputation: 23
I am trying to add an amount count down to my website header until free shipping is enabled.
Here is my code:
if ( ! function_exists( 'setup_free_shipping_counter' ) ) {
function setup_free_shipping_counter() {
ob_start();
?>
/* ... */
<p class="label-active"><span><?php echo get_shipping_cost_progress() ?></span> till free shipping</p>
/* ... */
<?php
return ob_get_clean();
}
}
add_shortcode('myshortcode', 'setup_free_shipping_counter');
function get_shipping_cost_progress() {
$min_amount = 50;
$current = WC()->cart->subtotal;
$progress = wc_price( $min_amount - $current );
return $progress;
}
The problem is that on cart Ajax events like Ajax add to cart, remove item from cart, change cart item quantity, the progress doesn't get updated.
How can I make my Shortcode get updated on woocommerce Ajax cart events?
If I reload page then Shortcode shows correct progress, but I need to make it to update dynamically on cart Ajax events.
Upvotes: 2
Views: 696
Reputation: 253773
You need to use dedicated woocommerce_add_to_cart_fragments
action hook (Ajax powered), to get your custom progress count refreshed when cart changes on Ajax requests.
I have revisited your code a bit (to change the display, when free shipping is enabled):
// Shortcode: [fs_progress]
function display_free_shipping_progress() {
return get_free_shipping_progress();
}
add_shortcode('fs_progress', 'display_free_shipping_progress');
// Function that makes calculations and display
function get_free_shipping_progress() {
$min_amount = 100; // Set the min amount to get free shipping
$prodgress = $min_amount - WC()->cart->subtotal;
if( $prodgress >= 0 ) {
return '<p id="fs-progress" class="label-active"><span>' . wc_price( $prodgress ) . '</span> '. __("till free shipping") .'</p>';
} else {
return '<p id="fs-progress" class="label-active">'. __("Free shipping is enabled!") .'</p>';
}
}
// Refreshing "free shipping" progress on cart ajax events
add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_free_shipping_progress' );
function refresh_free_shipping_progress( $fragments ){
$fragments['#fs-progress'] = get_free_shipping_progress();
return $fragments;
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Shortcode usage: [fs_progress]
Or in php code: echo do_shortcode( '[fs_progress]' );
Related: Ajaxify header cart items count in Woocommerce
Upvotes: 2