Search only posts (not pages) in WordPress

To search for only posts (not pages) in WordPress, you can make use of the pre_get_posts filter and modify the main query before it is executed. Here’s an example of how you can achieve this:

1. Open the theme’s functions.php file in your WordPress theme directory.
2. Add the following code to the file:

 

function exclude_other_post_from_search($query) {
    if (is_search() && !is_admin()) {
        $query->set('post_type',array('post','page'));
    }
}
add_action('pre_get_posts', 'exclude_other_post_from_search');

3. Save the changes and upload the modified functions.php file back to your server.

 

This code hooks into the pre_get_posts action and modifies the query’s post_type parameter to include only posts when a search is being performed and not when the request is made from the WordPress admin area.

After making these changes, the search results will only display posts and pages, excluding any other post type from the results.

Leave a Comment

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