Uses the pre_get_posts hook to exclude selected WooCommerce products from appearing across frontend queries, including shop pages, search results, feeds, and product archives. The products remain accessible via direct links but are hidden from public listings.
Useful for hiding discontinued, private, or restricted products without deleting them.
add_action('pre_get_posts', 'prefix_exclude_products_everywhere');
function prefix_exclude_products_everywhere($query) {
// Prevent running in admin or secondary queries
if (is_admin() || !$query->is_main_query()) {
return;
}
// Add product IDs to exclude
$excluded_products = array(123, 456, 789);
// Apply exclusion across frontend queries
if ($query->is_home() || $query->is_search() || $query->is_feed() || $query->is_post_type_archive('product') || $query->is_tax()) {
$query->set('post__not_in', $excluded_products);
}
}
?>