Sam
Sam

Reputation: 591

WooCommerce Restrict Product by ID

I need to check if a specific product is being purchased using this code but it's not working.

function validate($data,$errors) { 

    if ( ( is_product() && get_the_ID() == 1566 ) || is_single('1566') ) {
    return;

$p = wc_get_product('1566');

$message = sprintf( __( '%s can only be purchased by some customers.</div>', 'text-domain' ), $p->get_name() );

        wc_add_notice( $message, 'error' );

    }
}
add_action('woocommerce_after_checkout_validation', 'validate',10,2);

Upvotes: 2

Views: 104

Answers (1)

mujuonly
mujuonly

Reputation: 11861

add_filter('woocommerce_after_checkout_validation', 'woocommerce_after_checkout_validation', 10, 2);

function woocommerce_after_checkout_validation($data, $errors) {

    foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
        $product = $values['data'];

        if ($product) {
            if (1566 === $product->get_id()) {
                $errors->add('terms', __('You cannot purchase this product.', 'woocommerce'));
            }
        }
    }
    return $data;
}

Upvotes: 3

Related Questions