Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get chosen shipping method title by its Id in WooCommerce

In WooCommerce includes\class-express-checkout-gateway.php file I am getting shipping method Id by the following code:

$chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');

It gets flat_rate:1, but I need its title - Flat Rate.

I have already tried all this answers and many more.

How can I get this?

like image 801
SAUMYA Avatar asked Jun 08 '17 05:06

SAUMYA


People also ask

How do I get the selected shipping method in WooCommerce?

To do so, go to WooCommerce > Settings > Shipping, and select the shipping method you want to use.

How do I find the shipping ID in WooCommerce?

Right click on the 'Shipping' box of your checkout page when the option you need is available. The option ID can be found nearby in the source code, as seen below.


2 Answers

$rate_table = array();

$shipping_methods = WC()->shipping->get_shipping_methods();

foreach($shipping_methods as $shipping_method){
    $shipping_method->init();

    foreach($shipping_method->rates as $key=>$val)
        $rate_table[$key] = $val->label;
}

echo $rate_table[WC()->session->get( 'chosen_shipping_methods' )[0]]; 

Try like this

like image 145
mujuonly Avatar answered Nov 29 '22 00:11

mujuonly


If the customer has calculated the shipping on the front end, this should work:

function get_shipping_name_by_id( $shipping_id ) {
    $packages = WC()->shipping->get_packages();

    foreach ( $packages as $i => $package ) {
        if ( isset( $package['rates'] ) && isset( $package['rates'][ $shipping_id ] ) ) {
            $rate = $package['rates'][ $shipping_id ];
            /* @var $rate WC_Shipping_Rate */
            return $rate->get_label();
        }
    }

    return '';
}

This will return an empty string if it couldn't find a name for the given shipping id.

like image 34
hjoelr Avatar answered Nov 29 '22 00:11

hjoelr