WC_Shortcode_Cart::calculate_shipping()public staticWC 1.0

Calculate shipping for the cart.

Method of the class: WC_Shortcode_Cart{}

Return

null. Nothing (null).

Usage

$result = WC_Shortcode_Cart::calculate_shipping();

WC_Shortcode_Cart::calculate_shipping() code WC 9.4.2

public static function calculate_shipping() {
	try {
		WC()->shipping()->reset_shipping();

		$address = array();

		$address['country']  = isset( $_POST['calc_shipping_country'] ) ? wc_clean( wp_unslash( $_POST['calc_shipping_country'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
		$address['state']    = isset( $_POST['calc_shipping_state'] ) ? wc_clean( wp_unslash( $_POST['calc_shipping_state'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
		$address['postcode'] = isset( $_POST['calc_shipping_postcode'] ) ? wc_clean( wp_unslash( $_POST['calc_shipping_postcode'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.
		$address['city']     = isset( $_POST['calc_shipping_city'] ) ? wc_clean( wp_unslash( $_POST['calc_shipping_city'] ) ) : ''; // WPCS: input var ok, CSRF ok, sanitization ok.

		if ( $address['postcode'] ) {
			$address['postcode'] = wc_format_postcode( $address['postcode'], $address['country'] );
		}

		$address = apply_filters( 'woocommerce_cart_calculate_shipping_address', $address );

		if ( $address['postcode'] && ! WC_Validation::is_postcode( $address['postcode'], $address['country'] ) ) {
			throw new Exception( __( 'Please enter a valid postcode / ZIP.', 'woocommerce' ) );
		}

		if ( $address['country'] ) {
			if ( ! WC()->customer->get_billing_first_name() ) {
				WC()->customer->set_billing_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
			}
			WC()->customer->set_shipping_location( $address['country'], $address['state'], $address['postcode'], $address['city'] );
		} else {
			WC()->customer->set_billing_address_to_base();
			WC()->customer->set_shipping_address_to_base();
		}

		WC()->customer->set_calculated_shipping( true );
		WC()->customer->save();

		wc_add_notice( __( 'Shipping costs updated.', 'woocommerce' ), 'notice' );

		do_action( 'woocommerce_calculated_shipping' );

	} catch ( Exception $e ) {
		if ( ! empty( $e ) ) {
			wc_add_notice( $e->getMessage(), 'error' );
		}
	}
}