I'm setting up a woocommerce website, and I need that a product is purchasable by customers (users) that have a custom capability that equals the product brand name (the brand name is a product attribute). In this way i'm able to decide which user can buy products of each brand.
Searching online i found some code that I adapted for my needs:
// Disable purchase based on users capabilities
function check_brand_purchase_capability( $purchasable, $product ) {
// Don't run on parents of variations,
// this will already check variations separately
if ( $product->is_type( 'variable' ) ) {
return $purchasable;
}
global $product;
$brand_name = strtolower ( $product->get_attribute( 'pa_brand' ) );
// Check if user has the capability corresponding to the brand name
if ( current_user_can( $brand_name ) ) {
$purchasable = true;
} else {
$purchasable = false;
}
// Double-check for variations: if parent is not purchasable, then variation is not
if ( $purchasable && $product->is_type( 'variation' ) ) {
$purchasable = $product->parent->is_purchasable();
}
return $purchasable;
}
add_filter( 'woocommerce_variation_is_purchasable',
'check_brand_purchase_capability', 10, 2 );
add_filter( 'woocommerce_is_purchasable', 'check_brand_purchase_capability',
10, 2 );
With this code I correctly enable/disable the "add to cart" button whether the user has the correct capability or not.
The problem is that when the button is enable and I click "add to cart", the button hangs and nothing happens. Does anyone knows why this is happening? Thanks for the help