How to Exclude Pages in WordPress Search Results

By default, WordPress websites have a search feature that is useful for visitors to search for specific posts. However, this built-in search feature also involves Pages or page which should not be found.

This problem can be solved with a plugin, but there is an easier way to exclude Pages so that only Posts appear. A little technical, but very easy to implement.

Notes: The following tutorial uses WordPress 5.3.2 references with an English display. Even so, I’m pretty sure users with other languages ​​or versions can still follow suit.

1. Go to Appearance > Theme Editor.

2. Select functions.php in the right-hand bar.

functions.php How to Exclude Pages in WordPress Search Results 2 functions.php

3. Add the following code to functions.php then File Updates.

/*START EXCLUDE PAGE FROM SEARCH RESULT*/
function remove_pages_from_search() {
    global $wp_post_types;
    $wp_post_types['page']->exclude_from_search = true;
}
add_action('init', 'remove_pages_from_search');
/*END EXCLUDE PAGE FROM SEARCH RESULT*/
Update File How to Exclude Pages in WordPress Search Results 3 File Update

Please check your WordPress website to make sure that all Pages have been “removed” from search results so that only Posts are left.

How to exclude only certain pages?

To exclude certain pages, it’s a good idea to use a plugin named Search Exclude. This free plugin helps you set which Pages and Posts you want to exclude. In addition, you can include it again if you change your mind.

Does this effect stay the same when changing themes?

Given that the code was embedded in the theme’s functions.php, then when you change to another theme, the code will disappear so you need to add it again after activating the new theme.

See also  How to Create Ads.txt File for Adsense in WordPress