Adds a banner atop cart and checkout pages with dollar amount remaining to get free shipping. Currently set to $100 free shipping.
Block Cart – With AJAX refreshing
add_filter( 'woocommerce_package_rates', function( $rates, $cart_items ) {
// Skip When Free Shipping Is Available
foreach( $rates as $rate_id => $rate ) {
if( 'free_shipping' === $rate->method_id ) {
return $rates;
}
}
// Get Cart Subtotal
$subtotal = (float) WC()->cart->get_subtotal();
// Handle Free Shipping Threshold Reached
if( $subtotal >= 100 ) {
return $rates;
}
// Calculate Remainder
$remaining = 100 - $subtotal;
$remaining = sprintf(
'%s remaining to get free shipping on this order.',
html_entity_decode( strip_tags( wc_price( $remaining ) ) )
);
foreach( $rates as $rate_id => &$rate ) {
if( 'flat_rate' === $rate->method_id ) {
$rate->delivery_time = $remaining;
}
}
return $rates;
}, 10, 2 );
Block Cart or Checkout – Non AJAX
add_filter( 'render_block', function( $block_content, $block ) {
// Cart or Checkout Shipping Block Only
if(
$block['blockName'] !== 'woocommerce/cart-order-summary-shipping-block'
&& $block['blockName'] !== 'woocommerce/checkout-order-summary-shipping-block'
) {
return $block_content;
}
// Handle Null Cart
if( empty( WC()->cart ) ) {
return $block_content;
}
// Get Cart Subtotal
$subtotal = (float) WC()->cart->get_subtotal();
// Handle Free Shipping Threshold Reached
if( $subtotal >= 100 ) {
return $block_content;
}
// Calculate Remainder
$remaining = 100 - $subtotal;
// Output Message
return $block_content . sprintf(
'
<div class="woocommerce-info">
<strong>%s remaining to get free shipping on this order.</strong>
<a class="button" href="/shop/">Shop Now</a>
</div>
',
wc_price( $remaining )
);
}, 10, 2 );
Classic cart and Checkout
add_action( 'woocommerce_before_cart', function() {
do_action( 'ccom_free_shipping_calc' );
} );
add_action( 'woocommerce_before_checkout_form', function() {
do_action( 'ccom_free_shipping_calc' );
} );
add_action( 'ccom_free_shipping_calc', function() {
// Get Subtotal
$subtotal = WC()->cart->get_subtotal();
// Handle Free Shipping Threshold Reached
if( $subtotal >= 100 ) {
return;
}
// Calculate Remainder
$remaining = 100 - $subtotal;
// Output Message
printf(
'<div class="woocommerce-error"><strong>%s</strong></div>',
wc_price( $remaining )
. ' remaining to get free shipping on this order.'
);
} );