mercredi 28 octobre 2020

Optimize little Woocommerce snippet code with IF .. ElseIF and such

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;
}

Aucun commentaire:

Enregistrer un commentaire