Reputation: 543
I have a small bit of code which calculates the cart total (excluding taxes) and outputs a Free Shipping upsell, if the cart total is less than $50.
// Shipping Upsell
/**
* Checks the cart for the Total excluding taxes
* @param $total_required
* @return bool
*/
function qualifies_basedon_cart_total( $total_required ) {
/*
* We only want to run this on the cart or checkout page
* If the cart subtotal is less than $total_required for free shipping, return true
*/
if( is_cart() || is_checkout () ) {
if( WC()->cart->subtotal_ex_tax < $total_required ) {
return true;
}
}
// do nothing
return false;
}
function shipup(){
// tests if total is below $50 and displays upsell if query returns ture
if( qualifies_basedon_cart_total( 50 ) ) {
echo "<div class =\"shipup\"><h3>Free Shipping</h3>\n<p>Get free shipping on all orders over $50!</p></div>";
}
}
add_action ('woocommerce_cart_collaterals','shipup', 1);
The code above works great on the initial page load, but after changing the quantity on the cart page and selecting 'Update Cart' the code I have above (in functions.php) does not adjust itself based on the new cart total.
I believe the update cart button uses AJAX and my code is not able to tap into that. How can AJAXIFY my code so that it works based on the dynamic cart total?
Upvotes: 3
Views: 6026
Reputation: 11861
<?php
/* Update cart total on quantity change */
function cart_select_change_js() {
?>
<script type="text/javascript">
jQuery(document).ready(function($){
$(".product-quantity .quantity_select select.qty").change(function(){
$("section.entry .woocommerce").append('<div style="display:none" class="blockUI"></div>');
$("section.entry .woocommerce").append('<div style="z-index: 1000; border: medium none; margin: 0px; padding: 0px; width: 100%; height: 100%; top: 0px; left: 0px; background: url("/wp-content/plugins/woocommerce/assets/images/[email protected]") no-repeat scroll center center / 16px 16px rgb(255, 255, 255); opacity: 0.6; cursor: wait; position: absolute;" class="blockUI blockOverlay"></div>');
$(".actions input.button").click();
});
});
</script>
<?php
}
add_action('woocommerce_after_cart', 'cart_select_change_js', 10);
?>
Try this code snippet
Upvotes: 1
Reputation: 2046
If you're using WooCommerce 2.6 and above, WC has created a way to do this without additional code on your end.
You'll need to setup "Shipping Zones" under "WooCommerce" -> "Settings" -> "Shipping" -> "Shipping Zones".
For example, I have "Local" and "United States" shipping zones.
Now when the cart's total is $50 or more, then free shipping will be available.
Upvotes: 0