How to Search only Posts or Pages in WordPress

The WordPress default search function displays posts and pages in search results. This works for most WordPress users.

In certain conditions, you want to omit posts or pages from search results. For example, a blogger wants to search posts only as his/her most popular content belongs to posts.

For corporate or business sites pages are more important than blog posts they prefer pages in search results.

This can be achieved by using a small WordPress snippet.

Let’s check and test the code.

Search only WordPress Posts

Copy and paste the following code in your functions.php file to exclude pages from search.

    function wpclap_search_post($query) {
        if ($query->is_search) {
            $query->set('post_type', 'post');
        }
        return $query;
    }
	add_filter('pre_get_posts','wpclap_search_post');

Search only WordPress Pages

Copy and paste the following code in your functions.php file to exclude posts from search.

    function wpclap_search_page($query) {
        if ($query->is_search) {
            $query->set('post_type', 'page');
        }
        return $query;
    }
    add_filter('pre_get_posts','wpclap_search_page');

I hope this small snippet will help you to exclude posts or pages from WordPress search results.

Leave a Reply

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