Reputation: 407
We use the following code to hide products having categories "uncategorized":
add_action('pre_get_posts', 'custom_pre_get_posts_query');
function custom_pre_get_posts_query( $q ) {
if (!$q->is_main_query()) return;
if (!$q->is_post_type_archive()) return;
$q->set('tax_query', array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'ukategorisert',
'operator' => 'NOT IN',
)
));
remove_action('pre_get_posts', 'custom_pre_get_posts_query');
}
But for some reason, the archive ends up showing a different number of products on each page. It seems like the products are hidden, but still counted as products in the pagination?
We can't find a reason or solution for this problem. Please help.
Upvotes: 2
Views: 2264
Reputation: 253867
Instead of using pre_get_posts
hooked function, you should use one of the related dedicated Woocommerce action and filter hooks.
Try this instead:
add_filter('woocommerce_product_query_tax_query', 'custom_product_query_tax_query', 10, 2 );
function custom_product_query_tax_query( $tax_query, $query ) {
if( is_admin() ) return $tax_query;
// HERE Define your product category SLUGs to be excluded
$terms = array( 'ukategorisert' ); // SLUGs only
// The taxonomy for Product Categories
$taxonomy = 'product_cat';
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'slug', // Or 'name' or 'term_id'
'terms' => $terms,
'operator' => 'NOT IN', // Excluded
);
return $tax_query;
}
This code goes on function.php file of your active child theme (or theme). It should work.
Upvotes: 1