Show Only Posts in WordPress Search Results

Advanced Guides Code Snippets Coding Blog Content Management PHP PHP Debugging PHP Development PHP Snippets Wordpress WordPress Code Snippets WordPress Development WordPress Functions WordPress How-To WordPress Snippets WordPress Theme Development WordPress Tips WordPress Tutorials
✨

Show Only Posts in WordPress Search Results Tutorial/Guide

By default, WordPress search includes posts, pages, and sometimes custom post types. If you'd like to restrict searches to only blog posts, follow these steps. Step 1: Open your active theme’s functions.php file. Step 2: Insert this code:

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

Step 3: Save the file. Now, only posts will be shown in WordPress search results — pages and other types will be excluded automatically. This approach improves search relevance for blog-based websites by limiting the results to what users most likely expect: your blog content.  

πŸ’‘ Have a Coding Problem?

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