简体   繁体   中英

Targeting a particular product in woocommerce add to cart validation hook

I have 2 products in my site. Among them, for 1 product, if the user chooses more than 3 qty, I should display an error message. But for the other product, there is no limitation for the qty. How could i acheive this?

I have used the below code:

add_action( 'woocommerce_add_to_cart_validation', 'wc_add_to_cart_validation', 11, 3 ); 
function wc_add_to_cart_validation( $passed, $product_id, $quantity ) {

if ( $quantity > 3 ){
wc_add_notice( __( 'Only 3 or less quantities allowed, please contact us on (937) 606-4258.', 'woocommerce' ), 'error' );
$passed = false;
}
return $passed;
}

But the code reflects on both the products. I want the action to be performed only on one product Please help

To target a specific product ID (that you will define in the code), try this instead:

add_action( 'woocommerce_add_to_cart_validation', 'conditional_add_to_cart_validation', 15, 3 ); 
function conditional_add_to_cart_validation( $passed, $product_id, $quantity ) {
    // HERE below define your specific product ID
    $specific_product_id = 37;

    if ( $quantity > 3 && $product_id == $specific_product_id ){
        wc_add_notice( __( 'Only 3 or less quantities allowed, please contact us on (937) 606-4258.', 'woocommerce' ), 'error' );
        $passed = false;
    }
    return $passed;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM