Limit Search to Posts

In another snippet I showed you how to add custom post types to the main WordPress loop. Easily done with the pre_get_posts filter.

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.

function filter_search($query) {
    //---- Don't run in admin area
    if (is_admin()) {
        return $query;
    }
    
    //---- 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');

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.