How to Restrict WordPress Search to Posts Only

Code Snippets Coding Blog PHP PHP Development Theme Optimization Tutorials Wordpress WordPress Development WordPress Hacks WordPress Tips WP Best Practices

How to Restrict WordPress Search to Posts Only Tutorial/Guide

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.  

💡 Have a Coding Problem?

Search our archives or reach out to our team for solutions and expert advice.