WC_Form_Handler::add_to_cart_action()
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{}
Hooks from the method
Return
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() WC Form Handler::add to cart action code WC 9.5.1
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 ( 'variable' === $add_to_cart_handler || 'variation' === $add_to_cart_handler ) { $was_added_to_cart = self::add_to_cart_handler_variable( $product_id ); } elseif ( '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' ) ) { $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; } } }