wc_get_chosen_shipping_method_for_package()WC 3.2.0

Get chosen method for package from session.

Hooks from the function

Return

String|true|false. Either the chosen method ID or false if nothing is chosen yet.

Usage

wc_get_chosen_shipping_method_for_package( $key, $package );
$key(int) (required)
Key of package.
$package(array) (required)
Package data array.

Changelog

Since 3.2.0 Introduced.

wc_get_chosen_shipping_method_for_package() code WC 9.6.1

function wc_get_chosen_shipping_method_for_package( $key, $package ) {
	if ( ! is_callable( array( WC()->session, 'get' ) ) ) {
		return false;
	}

	$chosen_methods = WC()->session->get( 'chosen_shipping_methods', array() );
	$chosen_method  = isset( $chosen_methods[ $key ] ) ? $chosen_methods[ $key ] : false;
	$changed        = wc_shipping_methods_have_changed( $key, $package );

	// This is deprecated but here for BW compat. Remove in 4.0.0.
	$method_counts = WC()->session->get( 'shipping_method_counts' );

	if ( ! empty( $method_counts[ $key ] ) ) {
		$method_count = absint( $method_counts[ $key ] );
	} else {
		$method_count = 0;
	}

	if ( ! isset( $package['rates'] ) || ! is_array( $package['rates'] ) ) {
		$package['rates'] = array();
	}

	// If not set, not available, or available methods have changed, set to the DEFAULT option.
	if ( ! $chosen_method || $changed || ! isset( $package['rates'][ $chosen_method ] ) || count( $package['rates'] ) !== $method_count ) {
		$chosen_method          = wc_get_default_shipping_method_for_package( $key, $package, $chosen_method );
		$chosen_methods[ $key ] = $chosen_method;
		$method_counts[ $key ]  = count( $package['rates'] );

		WC()->session->set( 'chosen_shipping_methods', $chosen_methods );
		WC()->session->set( 'shipping_method_counts', $method_counts );

		/**
		 * Fires when a shipping method is chosen.
		 *
		 * @since 3.2.0
		 * @param string $chosen_method Chosen shipping method. e.g. flat_rate:1.
		 */
		do_action( 'woocommerce_shipping_method_chosen', $chosen_method );
	}
	return $chosen_method;
}