Add different custom labels to Woocommerce shippin

2019-08-02 18:07发布

问题:

In WooCommerce, I am trying to add "shipping estimates" to my shipping methods (all of them are flat rate type), so it looks like this:

Only all the estimated dates are different…

My problem is that I can't seem to target specific instances. I can only select entire method (flat rate), I checked for my methods instance ID's, since those are unique:

But it only works when I put 0 as a case in php switch method. 2,3,4,5,7 do not work.

Here is my code:

function sv_shipping_method_estimate_label($label, $method) {
    $label. = '<br /><small>';
    switch ($method - > instance_id) {
        case 0:
            $label. = 'Est delivery: 2-400 days';
            break;
    }

    $label. = '</small>';
    return $label;
}
add_filter('woocommerce_cart_shipping_method_full_label', 'sv_shipping_method_estimate_label', 10, 2);

The code obviously results in all the same estimates for all my shipping methods.


thanks!

im using this:

case 'flat_rate': $label .= 'Lieferzeit: 2-3 Tage flat'; break; case 'free_shipping': $label .= 'Lieferzeit: 2-3 Tage free'; break; case 'international_delivery': $label .= 'Lieferzeit: 4-5 Tage Inter'; break; default: $label .= 'Lieferzeit: 2-3 Tage default';

the international_delivery is not displaying 'Lieferzeit: 4-5 Tage Inter'. I gues I need to refer to it not as 'international_delivery' but something else. I tried 'flat_rate7' also not working.

I have set 2 shipping Zones 1 for Germany and the other is called Euro and contains the rest of european counties

回答1:

Here is the correct way to do what you are expecting (you should only need to change the texts to get your correct labels):

add_filter('woocommerce_cart_shipping_method_full_label', 'custom_shipping_method_label', 10, 2);
function custom_shipping_method_label( $label, $method ){
    $rate_id = $method->id; // The Method rate ID (Method Id + ':' + Instance ID)

    // Continue only if it is "flat rate"
    if( $method->method_id !== 'flat_rate' ) return $label;

    switch ( $method->instance_id ) {
        case '3':
            $txt = __('Est delivery: 2-5 days'); // <= Additional text
            break;
        case '4':
            $txt =  __('Est delivery: 1 day'); // <= Additional text
            break;
        case '5':
            $txt =  __('Est delivery: 2-3 days'); // <= Additional text
            break;
         // for case '2' and others 'flat rates' (in case of)
        default:
            $txt =  __('Est delivery: 2-400 days'); // <= Additional text
    }
    return $label . '<br /><small>' . $txt . '</small>';
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works