This topic has 2 replies, 1 voice, and was last updated 40 minutes ago ago by dybwpath
I use a custom code that hides products from a specific product category.
It works for archive page or other woo pages.
But for example it does not work to hide the products from xstore element “Products.”
I did not checked the Elementor default Products element becuase I would like to use the xstore element.
= = =
Code bellow:
add_action(‘pre_get_posts’, ‘hide_products_for_guests’);
function hide_products_for_guests($query) {
if (!is_admin() && $query->is_main_query()) {
// Specify the category slug or ID you want to restrict
$restricted_category = ‘category-slug’; // Replace with your category slug
// Check if the user is not logged in
if (!is_user_logged_in()) {
// Get the term ID of the category
$term = get_term_by(‘slug’, $restricted_category, ‘product_cat’);
// If the term exists, exclude products from this category
if ($term) {
$query->set(‘tax_query’, array(
array(
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘term_id’,
‘terms’ => $term->term_id,
‘operator’ => ‘NOT IN’,
),
));
}
}
}
}
= = =
I also tried to force it, but it didn’t work:
function hide_products_for_guests($query) {
if (!is_admin() && $query->is_post_type_archive(‘product’) || is_tax(‘product_cat’) || is_shop() || is_product_category()) {
// Specify the category slug or ID you want to restrict
$restricted_category = ‘category-slug’;
// Check if the user is not logged in
if (!is_user_logged_in()) {
// Get the term ID of the category
$term = get_term_by(‘slug’, $restricted_category, ‘product_cat’);
// If the term exists, exclude products from this category
if ($term) {
$tax_query = $query->get(‘tax_query’) ? $query->get(‘tax_query’) : [];
$tax_query[] = [
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘term_id’,
‘terms’ => $term->term_id,
‘operator’ => ‘NOT IN’,
];
$query->set(‘tax_query’, $tax_query);
}
}
}
}
add_action(‘woocommerce_product_query’, ‘hide_products_for_guests’);
Also, is there a way to exlude products or category in the xstore elementor element “Products” ?
You must be logged in to reply to this topic.Log in/Sign up