Created
January 5, 2025 10:18
-
-
Save gonzalesc/0a2bc6f3b6b467a5e880d3cfbfffb7cb to your computer and use it in GitHub Desktop.
Free Shipping method by Subtotal in WooCommerce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/********* | |
* Hooks | |
* Remember to remove shipping-transient-version transient | |
********/ | |
// Snippet 1 : Hide other shipping methods | |
add_filter( 'woocommerce_package_rates', 'maybeFreeShipping' ); | |
// Snippet 2 : Notify that the customer can access free shipping. | |
add_action( 'woocommerce_before_cart', 'noticeFreeShipping' ); | |
add_action( 'woocommerce_before_checkout_form', 'noticeFreeShipping' ); | |
/************** | |
* Functions | |
**************/ | |
/** | |
* Hide other shipping methods | |
* @param array $rates | |
* @return array | |
*/ | |
function maybeFreeShipping( array $rates ): array { | |
$minFreeShipping = 100; | |
$cartSubtotal = WC()->cart->get_displayed_subtotal(); | |
// Return Early | |
if ( $cartSubtotal < $minFreeShipping ) { | |
return $rates; | |
} | |
// FreeShipping is visible | |
foreach ( $rates as $rateID => $rate ) { | |
if ( 'free_shipping' === $rate->method_id ) { | |
continue; | |
} | |
unset( $rates[ $rateID ] ); | |
} | |
return $rates; | |
} | |
/** | |
* Print Notice on the cart and checkout page | |
* @return void | |
*/ | |
function noticeFreeShipping(): void { | |
$minFreeShipping = 100; | |
$cartSubtotal = WC()->cart->get_displayed_subtotal(); | |
// Return Early | |
if ( $cartSubtotal >= $minFreeShipping ) { | |
return; | |
} | |
$missingFreeShipping = $minFreeShipping - $cartSubtotal; | |
printf( | |
'<div class="woocommerce-info">%s</div>', | |
sprintf( | |
esc_html__( 'Agrega %s más a tu carrito para obtener el envío gratuito!', 'letsgo' ), | |
wc_price( $missingFreeShipping ) | |
) | |
); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment