I'm trying to prevent that visitors buying certain products based on product tags.
I'm using 'woocommerce_is_purchasable'
woocommerce filter but it doesn't work with variable products.
This is my code:
function remove_add_to_cart_for_tag_id ( $purchasable, $product ){
if( $product->get_tag_ids() == array(181)) {
$purchasable = false;
} else {
return $purchasable;
}
if ( $purchasable && $product->is_type( 'variation' ) ) {
$purchasable = $product->parent->is_purchasable();
}
return $purchasable;
}
add_filter( 'woocommerce_is_purchasable', 'remove_add_to_cart_for_tag_id', 10, 2 );
add_filter( 'woocommerce_variation_is_purchasable', 'remove_add_to_cart_for_tag_id', 10, 2 );
I've based my code on this example: Get is_purchasable hook working for Woocommerce product variations too
There is some errors and mistakes in your code. Try the following instead (to make it work with product variations too):
add_filter( 'woocommerce_is_purchasable', 'remove_add_to_cart_for_tag_id', 10, 2 );
add_filter( 'woocommerce_variation_is_purchasable', 'remove_add_to_cart_for_tag_id', 10, 2 );
function remove_add_to_cart_for_tag_id ( $purchasable, $product ){
// For product variations (from variable products)
if ( $product->is_type('variation') ){
$parent = wc_get_product( $product->get_parent_id() );
$tag_ids = $parent->get_tag_ids();
}
// For other product types
else {
$tag_ids = $product->get_tag_ids();
}
if( in_array( 181, $tag_ids ) ) {
$purchasable = false;
}
return $purchasable;
}
Code goes in function.php file of your active child theme (or active theme). It should work now.