For Woocommerce, I need a PHP snippet that will hide few products ID’s I will select for guests and customers.
My code attempt:
function dma_restrict_product() {
$user = wp_get_current_user();
$user_meta = get_userdata($user->ID);
$user_roles = $user_meta->roles;
global $product;
if( in_array( 'customer', (array) $user_roles ) && ( is_single('3759') ) ) {
return true;
add_filter('woocommerce_is_purchasable', 'woocommerce_cloudways_purchasable');
function woocommerce_cloudways_purchasable($cloudways_purchasable, $product) {
return ($product->id == 3759 ? false : $cloudways_purchasable);
}
} else if( in_array('administrator', (array) $user_roles) ) {
return true;
} else {
return false;
}
}
But it doesn’t work as I would like.
2
Answers
If you want to hide the product completly:
You can hide products by using the ID of the product and exclude it from the product query:
If you want to hide the add to cart button of product:
If you want to list the product with price, but only hide the "Add to Cart" button, you can do this with the
woocommerce_is_purchasable
hook, that will return false for your product ids and therefore will show the price, but in the place of "Add to Cart" button the notice "Product cannot be purchased" appears.There are 2 different request on your question (one in the title and another a bit different in the body):
1). To avoid guests and customers to purchase some defined products (hiding or disabling add to cart button), use the following:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
2). To hide completely some defined products from guests and customers, use the following:
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
Related: Hide a specific Woocommerce products from loop if they are in cart