Limit Search to Posts Only

In a previous snippet I showed you how to add CPTs (custom post types) to the main WordPress loop using the pre_get_posts filter.

The below snippet allows you to limit the WordPress search functionality to only show posts. This is really useful on blogs because by default WordPress will also search pages and media.

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');

Advertisement


Comments are closed for this post.

Advertisement

Inspirational Newsletter

Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.