You need to use something different as following (commented):
// Loop through shipping packages from WC_Session (They can be multiple in some cases)
foreach ( WC()->cart->get_shipping_packages() as $package_id => $package ) {
// Check if a shipping for the current package exist
if ( WC()->session->__isset( 'shipping_for_package_'.$package_id ) ) {
// Loop through shipping rates for the current package
foreach ( WC()->session->get( 'shipping_for_package_'.$package_id )['rates'] as $shipping_rate_id => $shipping_rate ) {
$rate_id = $shipping_rate->get_id(); // same thing that $shipping_rate_id variable (combination of the shipping method and instance ID)
$method_id = $shipping_rate->get_method_id(); // The shipping method slug
$instance_id = $shipping_rate->get_instance_id(); // The instance ID
$label_name = $shipping_rate->get_label(); // The label name of the method
$cost = $shipping_rate->get_cost(); // The cost without tax
$tax_cost = $shipping_rate->get_shipping_tax(); // The tax cost
$taxes = $shipping_rate->get_taxes(); // The taxes details (array)
}
}
}
Now if customer session is not yet enabled (customer hasn’t add to cart any product yet), you need to force WooCommerce customer session activation using the following:
// Enable customer WC_Session add_action( 'init', 'wc_session_enabler' ); function wc_session_enabler() { if ( is_user_logged_in() || is_admin() ) return; if ( isset(WC()->session) && ! WC()->session->has_session() ) { WC()->session->set_customer_session_cookie( true ); } }
Code goes in functions.php file of your active child theme (or active theme).
If needed, you can also get the customer chosen shipping method(s) with the following:
$chosen_shipping_methods = WC()->session->get( 'chosen_shipping_methods' );