WC_Form_Handler::add_to_cart_handler_variable
Handle adding variable products to the cart.
Method of the class: WC_Form_Handler{}
Hooks from the method
Returns
true|false. success or not
Usage
$result = WC_Form_Handler::add_to_cart_handler_variable( $product_id );
- $product_id(int) (required)
- Product ID to add to the cart.
Changelog
| Since 2.4.6 | Introduced. |
| Since 2.4.6 | Split from add_to_cart_action. |
WC_Form_Handler::add_to_cart_handler_variable() WC Form Handler::add to cart handler variable code WC 10.6.2
private static function add_to_cart_handler_variable( $product_id ) {
$variation_id = empty( $_REQUEST['variation_id'] ) ? '' : absint( wp_unslash( $_REQUEST['variation_id'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$quantity = empty( $_REQUEST['quantity'] ) ? 1 : wc_stock_amount( wp_unslash( $_REQUEST['quantity'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$variations = array();
$product = wc_get_product( $product_id );
foreach ( $_REQUEST as $key => $value ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( 'attribute_' !== substr( $key, 0, 10 ) ) {
continue;
}
$variations[ sanitize_title( wp_unslash( $key ) ) ] = wp_unslash( $value );
}
$passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations );
if ( ! $passed_validation ) {
return false;
}
// Prevent parent variable product from being added to cart.
if ( empty( $variation_id ) && $product && $product->is_type( ProductType::VARIABLE ) ) {
$current_url = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ) : '';
$product_url = wp_parse_url( get_permalink( $product_id ), PHP_URL_PATH );
$is_in_product_page = $current_url && $product_url && untrailingslashit( $current_url ) === untrailingslashit( $product_url );
if ( $is_in_product_page ) {
/* translators: 1: product name */
$error_message = sprintf( __( 'Please choose product options for %1$s.', 'woocommerce' ), esc_html( $product->get_name() ) );
} else {
/* translators: 1: product link, 2: product name */
$error_message = sprintf( __( 'Please choose product options by visiting <a href="%1$s" title="%2$s">%2$s</a>.', 'woocommerce' ), esc_url( get_permalink( $product_id ) ), esc_html( $product->get_name() ) );
}
wc_add_notice( $error_message, 'error' );
return false;
}
if ( false !== WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variations ) ) {
wc_add_to_cart_message( array( $product_id => $quantity ), true );
return true;
}
return false;
}