categories – Restricted category in Woocommerce
I’m trying to do the following:
I need a restricted category for adults in Woocommerce.
Products in this category cannot appear anywhere else in the store or in search, only in the restricted category itself.
I didn’t find any free module that did this function but I found Age Gate that allows you to verify age in a specific category, however, it does not hide the products.
I researched a lot and didn’t find a ready code, I asked for help in many places but nobody helped, so I did more open searches and found some codes, joined parts of them and managed to make something that works.
I don’t understand PHP programming nor how to apply it correctly in Woocommerce but I could make the code work, I don’t know if it’s correct or if it’s the best way to program this, but it works.
The small problem is that when the product is assigned only the restricted category everything is ok, but when the product is assigned to more than one category, one of them being the restricted one, the code is removing the product from the entire store (except the restricted category) , I would like the product to be hidden only when it is only in the restricted category.
I think I need to check if the product is ONLY in the restricted category, but I don’t know how to do it.
Can anyone help me with the code?
Example:
How I would like:
Product in restricted category + candy category.
It appears normal throughout the site and search.
Product only in restricted category.
It only appears in the restricted category.
How it’s working now:
Product in restricted category + candy category.
It appears in the restricted category but not in the sweets category or in the search.
Product only in restricted category.
It only appears in the restricted category (okay).
This is the code I “made” (I’m using in functions.php):
$current_cat = get_queried_object();
if( $current_cat->slug != "restricted" ) {
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'restricted',
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
}
add_action( 'woocommerce_product_query', 'exclude_category_archive_products' );
Thank you very much.
Leave an answer