Would you please help me out to optimize my little snippet I wrote to apply a discount after adding products in the cart with tech
assigned shipping class and other products with no class specified for WordPress (Woocommerce) website.
How can I optimize the if .. elseif
and overall make it better. Also, is adding break
a good practise? I’m a PHP newbie, but I’m currently learning and would like to improve my code. Porbably I can use something similar to switch
? Any help and examples are greatly appreciated!
add_filter( 'woocommerce_package_rates', 'adjustment_in_rates_of_product_with_shipping_class', 12, 2 );
function adjustment_in_rates_of_product_with_shipping_class( $available_shipping_methods, $package ) {
// Shipping class slug to be eligible for a discount when combined with no class products
$shipping_class = array(
'tech',
);
// Discount
$discounteuro = 3.50;
$discountgbp = 3.20;
$discountusd = 4;
$discountglobalusd = 5;
// Enter the shipping method value
$shipping_services = array(
'flat_rate:5',
);
$shipping_class_exists = false;
foreach(WC()->cart->get_cart_contents() as $key => $values) {
if ( in_array($values['data']->get_shipping_class() , $shipping_class) ) {
$shipping_class_exists = true;
break;
}
}
$shipping_class_no_exists = false;
foreach(WC()->cart->get_cart_contents() as $key => $values) {
if ( strlen($values['data']->get_shipping_class()) == 0 ) {
$shipping_class_no_exists = true;
break;
}
}
if ($shipping_class_exists && $shipping_class_no_exists) {
foreach ($available_shipping_methods as $key => $value) {
if ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'EUR' ) {
$available_shipping_methods[$key]->cost -= $discounteuro;
break;
}
elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'GBP' ) {
$available_shipping_methods[$key]->cost -= $discountgbp;
break;
}
elseif ( in_array($value->get_id() , $shipping_services) && get_woocommerce_currency() == 'USD' ) {
$available_shipping_methods[$key]->cost -= $discountusd;
break;
}
else {
$available_shipping_methods[$key]->cost -= $discountglobalusd;
break;
}
}
}
return $available_shipping_methods;
}
2
Answers
I would combine your first two loops into a single loop, because there isn o reason to loop over the data twice. Something like this
I would also convert your discounts into an array, to make it easier to call from your loop.
Then your loop would become
Updated 2 Removed some mistakes
The following optimized code should do the trick (code is commented):
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Note: You should empty your after saving this code.