Skip to content

Instantly share code, notes, and snippets.

@grayayer
Created February 10, 2020 19:52
Show Gist options
  • Save grayayer/6a7d9065d50c0289b5ae009a5d8a3321 to your computer and use it in GitHub Desktop.
Save grayayer/6a7d9065d50c0289b5ae009a5d8a3321 to your computer and use it in GitHub Desktop.
Shows a message at the WooCommerce cart/checkout displaying how much customer needs to add to get free shipping. Only shows if there are items in cart
/**
* Show a message at the cart/checkout displaying
* how much to go for free shipping.
*/
function wc_free_shipping_incentive_notice() {
if ( ! is_cart() && ! is_checkout() && ( WC()->cart->get_cart_contents_count() == 0 ) ) {
return;
}
$packages = WC()->cart->get_shipping_packages();
$package = reset( $packages );
$zone = wc_get_shipping_zone( $package );
$current = WC()->cart->subtotal;
$cart_total = WC()->cart->get_displayed_subtotal();
if ( WC()->cart->display_prices_including_tax() ) {
$cart_total = round( $cart_total - ( WC()->cart->get_discount_total() + WC()->cart->get_discount_tax() ), wc_get_price_decimals() );
}
else {
$cart_total = round( $cart_total - WC()->cart->get_discount_total(), wc_get_price_decimals() );
}
foreach ( $zone->get_shipping_methods( true ) as $k => $method ) {
$min_amount = $method->get_option( 'min_amount' );
if ( $current < $min_amount ) {
$added_text = 'Get free shipping if you order ' . wc_price( $min_amount - $current ) . ' more!';
$return_to = wc_get_page_permalink( 'shop' );
$notice = sprintf( '<a href="%s" class="button wc-forward">%s</a> %s', esc_url( $return_to ), 'Continue Shopping', $added_text );
wc_print_notice( $notice, 'notice' );
}
}
}
add_action( 'woocommerce_before_cart', 'wc_free_shipping_incentive_notice' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment