Skip to main content

Hide Products from Search

To hide Anycover products from Wordpress search, go to the Theme File Editor in the Tools section and add the following code snippet to the bottom of the file:

    //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 = 'anycover'; // 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 );
}
}
}