//CUSTOM_SNIPPET
// MAKE SURE TO BACKUP YOUR FILE BEFORE ADDING THIS CODE SNIPPET
add_action( 'pre_get_posts', 'hide_products_from_search' );
function hide_products_from_search( $query ) {
if ( ! is_admin() && $query->is_search() && $query->is_main_query() ) {
$exclude_ids = array(); // create an empty array to store the IDs of the products to be excluded
$exclude_word = 'exclude me'; // replace with the word to be excluded from the search results
// get an array of all the products matching the search query
$args = array(
'post_type' => 'product',
's' => get_search_query(),
'posts_per_page' => -1,
'fields' => 'ids',
);
$product_ids = get_posts( $args );
// loop through the product IDs and check if the title contains the exclude word
foreach ( $product_ids as $product_id ) {
$product_title = get_the_title( $product_id );
if ( strpos( $product_title, $exclude_word ) !== false ) {
$exclude_ids[] = $product_id; // add the product ID to the exclude array
}
}
// set the 'post__not_in' parameter to exclude the products matching the exclude pattern
if ( ! empty( $exclude_ids ) ) {
$query->set( 'post__not_in', $exclude_ids );
}
}
}