How to remove your front page from WordPress search results

If you use a static front page for your WordPress site, depending on its contents and structure it may show up in your search results – you may (or may not) want this to happen.

If you don’t want to see your front page in your search results, add this code to your functions.php file:

add_action( 'pre_get_posts', 'edinburgh_wp_exclude_front_page_from_search' );
function edinburgh_wp_exclude_front_page_from_search( $query ) {
    if ( $query->is_main_query() && $query->is_search() ) {
        // Get an array with page ID of front page 
	$pageID = array(get_option('page_on_front'));
 	$query->set('post__not_in', $pageID);
    }
}

If you use a ‘regular’ setup and have a home page and not a static front page, use this slightly different function to exclude the home page from search results.

add_action( 'pre_get_posts', 'edinburgh_wp_exclude_home_page_from_search' );
function edinburgh_wp_exclude_home_page_from_search( $query ) {
    if ( $query->is_main_query() && $query->is_search() ) {
        // Get an array with page ID of home page
	$pageID = array(get_option('page_for_posts'));
 	$query->set('post__not_in', $pageID);
    }
}

What do you think?

Your email address will not be published. Required fields are marked *