How to limit WordPress search results to posts only during theme development

The default WordPress search system searches for posts, pages, authors, files and media in the wp-uploads directory. Sometimes you may want to limit this search to posts only when developing a theme or when taking your site to the production.

It’s a good practice to always limit the search results to posts only. If you have a lot of pages, you can also include pages in the search result.

This article is going to illustrate how to limit WordPress search to posts only.

Also Read: How to add CSS class to li and links in wp_nav_menu()

How to Limit WordPress Search to Posts Only During WordPress Theme Development.

To limit search results to posts only in WordPress, kindly add the following code into the funtions.php file of your theme.

function filter_search($query) {
    //---- Don't run in admin area
    if(!is_admin()) {
        // Limit search to posts
        if($query->is_main_query() && $query->is_search()) {
            $query->set('post_type', array('post'));

        // Return query
        return $query;

add_filter('pre_get_posts', 'filter_search');



Similar Posts