To exclude specific pages from WordPress search results, you can use the pre_get_posts
filter to modify the search query and exclude the desired pages. Here’s an example of how you can achieve this:
function wpsnippets_exclude_pages_from_search( $query ) {
if ( ! is_admin() && $query->is_search() ) {
// Array of page IDs to exclude from search
$exclude_pages = array( 2, 5, 8 );
$query->set( 'post__not_in', $exclude_pages );
}
}
add_action( 'pre_get_posts', 'wpsnippets_exclude_pages_from_search' );
In this example, $exclude_pages
is an array of page IDs that you want to exclude from search results. Replace the page IDs with the actual IDs of the pages you want to exclude.
Inside the wpsnippets_exclude_pages_from_search()
function, the is_search()
function is used to check if the current query is a search query. Then, the post__not_in
parameter of the query is set to the array of page IDs ($exclude_pages
), which excludes those pages from the search results.
By adding this code snippet to your WordPress site, you can exclude the specified pages from the search results. When users perform a search, the excluded pages will not appear in the search results.