WC_Form_Handler::add_to_cart_actionpublic staticWC 1.0

Add to cart action.

Checks for a valid request, does validation (via hooks) and then redirects if valid.

Method of the class: WC_Form_Handler{}

Returns

null. Nothing (null).

Usage

$result = WC_Form_Handler::add_to_cart_action( $url );
$url(true|false)
.
Default: false) URL to redirect to

WC_Form_Handler::add_to_cart_action() code WC 10.7.0

public static function add_to_cart_action( $url = false ) {
	if ( ! isset( $_REQUEST['add-to-cart'] ) || ! is_numeric( wp_unslash( $_REQUEST['add-to-cart'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		return;
	}

	wc_nocache_headers();

	$product_id        = apply_filters( 'woocommerce_add_to_cart_product_id', absint( wp_unslash( $_REQUEST['add-to-cart'] ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$was_added_to_cart = false;
	$adding_to_cart    = wc_get_product( $product_id );

	if ( ! $adding_to_cart ) {
		return;
	}

	$add_to_cart_handler = apply_filters( 'woocommerce_add_to_cart_handler', $adding_to_cart->get_type(), $adding_to_cart );

	if ( ProductType::VARIABLE === $add_to_cart_handler || ProductType::VARIATION === $add_to_cart_handler ) {
		$was_added_to_cart = self::add_to_cart_handler_variable( $product_id );
		$product_id        = ! empty( $_REQUEST['variation_id'] ) ? absint( wp_unslash( $_REQUEST['variation_id'] ) ) : $product_id; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
	} elseif ( ProductType::GROUPED === $add_to_cart_handler ) {
		$was_added_to_cart = self::add_to_cart_handler_grouped( $product_id );
	} elseif ( has_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler ) ) {
		do_action( 'woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url ); // Custom handler.
	} else {
		$was_added_to_cart = self::add_to_cart_handler_simple( $product_id );
	}

	// If we added the product to the cart we can now optionally do a redirect.
	if ( $was_added_to_cart && 0 === wc_notice_count( 'error' ) ) {
		$quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $_REQUEST['quantity'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended

		/**
		 * Fires when an item is added to the cart from a user request.
		 *
		 * @param int       $product_id Product ID.
		 * @param int|float $quantity   Quantity added to the cart.
		 *
		 * @since 10.6.0
		 */
		do_action( 'internal_woocommerce_cart_item_added_from_user_request', $product_id, $quantity );

		$url = apply_filters( 'woocommerce_add_to_cart_redirect', $url, $adding_to_cart );

		if ( $url ) {
			wp_safe_redirect( $url );
			exit;
		} elseif ( 'yes' === get_option( 'woocommerce_cart_redirect_after_add' ) ) {
			wp_safe_redirect( wc_get_cart_url() );
			exit;
		}
	}
}