diff --git a/includes/class-wc-form-handler.php b/includes/class-wc-form-handler.php index d91e18d7007..d6a60d15a9f 100644 --- a/includes/class-wc-form-handler.php +++ b/includes/class-wc-form-handler.php @@ -885,10 +885,12 @@ class WC_Form_Handler { * @return bool success or not */ 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 + $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; @@ -899,7 +901,22 @@ class WC_Form_Handler { $passed_validation = apply_filters( 'woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations ); - if ( $passed_validation && false !== WC()->cart->add_to_cart( $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->is_type( 'variable' ) ) { + $url = get_permalink( $product_id ); + $product_name = $product->get_name(); + + /* translators: %1$s: Product link, %2$s: Product title, %3$s: Product name. */ + wc_add_notice( sprintf( __( 'Please choose product options by visiting %3$s.', 'woocommerce' ), esc_url( $url ), esc_html( $product_name ), esc_html( $product_name ) ), '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; }