Prevent variable product from adding to cart when no variations are selected closes #27756

This commit is contained in:
roykho 2020-10-26 11:21:28 -07:00
parent 19e4c7ac7c
commit 3b022be68b
No known key found for this signature in database
GPG Key ID: 9B06F996CD4ECB92
1 changed files with 20 additions and 3 deletions

View File

@ -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 <a href="%1$s" title="%2$s"><u>%3$s</u></a>.', '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;
}