How to Limit or Restrict search for blog post only in WordPress

The below snippet allows you to limit the WordPress search functionality, so you show only posts. It’s really useful on blogs because, by default, WordPress will also search pages and media.

Open your functions.php file and add the following codes:

function searchfilter($query) { if ($query->is_search && !is_admin() ) { $query->set(‘post_type’,array(‘post’,’page’)); } return $query; } add_filter(‘pre_get_posts’,’searchfilter’);

Notice the line that says :


You can filter the search results by changing the values in the array variable. Right now it is set to display posts and pages but you can modify it to display anything you want.

Leave a Comment

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