When searching my own site, I noticed that certain pages, like a bookmarks page, were appearing in the search results. This creates a poor user experience, as visitors find irrelevant content. To fix this, you can exclude specific pages, posts, or custom post types from WordPress search results.
The solution involves adding a few lines of code to your theme's functions.php file or using a code snippets plugin. Below are several corrected and improved code examples.
Exclude Posts or Pages by ID
This code removes specific posts or pages from search results using their IDs.
// Exclude specific posts/pages from search by ID
function exclude_posts_from_search_by_id($query) {
if ( !$query->is_admin && $query->is_search ) {
// Add the IDs to exclude in the array, e.g., array(40, 819)
$query->set('post__not_in', array(40, 819));
}
return $query;
}
add_filter('pre_get_posts', 'exclude_posts_from_search_by_id');
Exclude Posts by Category
This code excludes all posts belonging to specific categories from search results.
// Exclude posts from specific categories in search
function exclude_category_from_search($query) {
if ( !$query->is_admin && $query->is_search ) {
// Prefix category IDs with a minus sign to exclude them, e.g., '-15,-57'
$query->set('cat', '-15,-57');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category_from_search');
Exclude All Pages from Search
This code limits search results to only standard 'posts', excluding all 'pages'.
// Exclude all pages from search results
function exclude_pages_from_search($query) {
if ( $query->is_search ) {
$query->set('post_type', 'post');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_pages_from_search');
Exclude a Custom Post Type
This code modifies which post types are included in search. The example excludes a custom post type named 'site'.
// Exclude a custom post type (e.g., 'site') from search
function exclude_cpt_from_search($query) {
if ( !is_admin() && $query->is_main_query() && $query->is_search ) {
// Define the post types TO INCLUDE in search
$query->set('post_type', array('post', 'page'));
}
}
add_action('pre_get_posts', 'exclude_cpt_from_search');
Usage Notes: Add only the code you need to your theme's functions.php file. Modify the IDs, category IDs, or post type arrays according to your requirements. If using multiple filters, ensure their logic does not conflict.