How to make Local Pickup method be chosen based on cart total in Woocommerce?
How to make Local Pickup method be chosen based on cart total in Woocommerce?
I want to make local pickup shipping method be chosen with radio input based on the cart total. I used this code
add_filter('woocommerce_package_rates', 'custom_modify_shipping_methods', 10, 2);
function custom_modify_shipping_methods($rates, $package) {
// Get the cart total
$cart_total = WC()->cart->subtotal;
// Set the threshold for choosing the local pickup shipping method
$threshold_amount = 2500;
// Check if the cart total is less than the threshold
if ($cart_total < $threshold_amount) {
// Loop through shipping rates
foreach ($rates as $rate_id => $rate) {
// Check if it's a local pickup method
if (strpos($rate_id, 'local_pickup') !== false) {
// Set the cost to zero (free)
$rates[$rate_id]->cost = 0;
}
}
}
return $rates;
}
This code unset all shipping methods, it shows local pick up label not the radio type input. The input type is hidden and I can not proceed to payment as the shipping method is not selected. How can I modify the code to make local pick up method default chosen others unset if the cart total is less than 2500?
When there is only one available shipping method, the corresponding radio input button is hidden and this available shipping method is automatically selected by WooCommerce…
The code that you are using is not adapted to your needs. Instead, use the following:
add_filter( 'woocommerce_package_rates', 'filter_shipping_package_rates', 10, 2 );
function filter_shipping_package_rates( $rates, $package ) {
$threshold_amount = 2500; // Here set the threshold amount
$subtotal_amount = 0; // Initializing variable
// Loop through cart items for the current shipping package
foreach( $package['contents'] as $item ){
$subtotal_amount += $item['line_subtotal'] + $item['line_subtotal_tax'];
}
// If cart items subtotal is up to the defined threshold amount
if ( $subtotal_amount >= $threshold_amount ) {
// Loop through shipping rates for the current shipping package
foreach( $rates as $rate_key => $rate ) {
// Targeting local pickup
if( 'local_pickup' === $rate->method_id ) {
$taxes = array(); // Initializing variable
// Loop through tax costs
foreach ($rate->taxes as $key => $tax) {
$taxes[$key] = 0; // Set tax cost to zero
}
$rates[$rate_key]->cost = 0; // Set cost to zero
$rates[$rate_key]->taxes = $taxes; // Set back taxes costs array
} else {
unset($rates[$rate_key]); // Remove other rates
}
}
}
return $rates;
}
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
Always empty your cart, to refresh cached shipping data.
January 7, 2024
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand
January 7, 2024