How to Restrict WordPress Search to Posts Only

If you want WordPress to return only blog posts in search results, excluding pages or custom types, use the pre_get_posts filter to modify the default behavior.

Step 1: Open your theme’s functions.php file.

Step 2: Add the following code snippet:

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

Step 3: Save the file and re-upload it to your server if needed.

This code ensures that search results only include standard blog posts and exclude all other post types, including pages. It works only on the front end and won’t affect admin area queries.

 

Leave a Comment

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

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.