wc_get_default_shipping_method_for_package()
Choose the default method for a package.
Hooks from the function
Returns
String.
Usage
wc_get_default_shipping_method_for_package( $key, $package, $chosen_method );
- $key(int) (required)
- Key of package.
- $package(array) (required)
- Package data array.
- $chosen_method(string) (required)
- Chosen shipping method. e.g. flat_rate:1.
Changelog
| Since 3.2.0 | Introduced. |
wc_get_default_shipping_method_for_package() wc get default shipping method for package code WC 10.7.0
function wc_get_default_shipping_method_for_package( $key, $package, $chosen_method ) {
$rate_keys = array_keys( $package['rates'] );
$local_pickup_method_ids = LocalPickupUtils::get_local_pickup_method_ids();
if ( 'shortcode' === WC()->cart->cart_context ) {
$default = current( $rate_keys );
} else {
// No default means that when you enter block checkout, shipping is chosen rather than pickup. We should only do this if there are shipping methods available other than local pickup.
$default = CartCheckoutUtils::shipping_methods_exist() ? '' : current( $rate_keys );
// Default to the first method in the package that isn't a local pickup method.
foreach ( $rate_keys as $rate_key ) {
$rate_method_id = current( explode( ':', $rate_key ) );
if ( ! in_array( $rate_method_id, $local_pickup_method_ids, true ) ) {
$default = $rate_key;
break;
}
}
}
/**
* If the customer has selected local pickup, keep it selected if it's still in the package. We don't want to auto
* toggle between shipping and pickup even if available shipping methods are changed.
*
* This is important for block-based checkout where there is an explicit toggle between shipping and pickup.
*/
$chosen_method_id = current( explode( ':', $chosen_method ) );
$chosen_method_exists = in_array( $chosen_method, $rate_keys, true );
$is_local_pickup_chosen = in_array( $chosen_method_id, $local_pickup_method_ids, true );
// Default to local pickup if its chosen already.
if ( $chosen_method_exists && $is_local_pickup_chosen ) {
$default = $chosen_method;
} else {
// Check coupons to see if free shipping is available. If it is, we'll use that method as the default.
$coupons = WC()->cart->get_coupons();
foreach ( $coupons as $coupon ) {
if ( $coupon->get_free_shipping() ) {
foreach ( $rate_keys as $rate_key ) {
if ( 0 === stripos( $rate_key, 'free_shipping' ) ) {
$default = $rate_key;
break;
}
}
break;
}
}
}
/**
* Filters the default shipping method for a package.
*
* @since 3.2.0
* @param string $default Default shipping method.
* @param array $rates Shipping rates.
* @param string $chosen_method Chosen method id.
*/
return (string) apply_filters( 'woocommerce_shipping_chosen_method', $default, $package['rates'], $chosen_method );
}