1
votes

How can I retrieve the shipping methods that are visible to the end user? ( not all shipping methods defined in Woocommerce ). I am using the "Shipping Zones by Drawing for WooCommerce" plugin. I need multiple radiuses around the store. The issue is that I have more than one and this plugin will only hide the radius where the user is located outside of it and will show the rest ( I need to show only one of them, the cheapest ).

I have tried to print the rates from woocommerce_package_rates and WC()->session but these will show all shipping methods defined including the one that it is not shown the user.

1

1 Answers

1
votes

To get the costumer available shipping methods when shipping location is defined and when cart is not empty, you can use:

// Get shipping packages
$shipping_packages = WC()->cart->get_shipping_packages();

foreach( array_keys( $shipping_packages ) as $key ) {
    if( $shipping_for_package = WC()->session->get('shipping_for_package_'.$key) ) {
        if( isset($shipping_for_package['rates']) ) {
            // Loop through customer available shipping methods
            foreach ( $shipping_for_package['rates'] as $rate_key => $rate ) {
                $rate_id = $rate->id; // the shipping method rate ID (or $rate_key)
                $method_id = $rate->method_id; // the shipping method label
                $instance_id = $rate->instance_id; // The instance ID
                $cost = $rate->label; // The cost
                $label = $rate->label; // The label name
                $taxes = $rate->taxes; // The taxes (array)
                print_pr($label);
            }
        }
    }
}

Now to get the chosen shipping method you will use:

WC()->session->get('chosen_shipping_methods'); // (Array)