Advertisement

Limit Search to Posts Only

In anpther 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()) {
        // 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

Web designer and developer from Southampton, UK.


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.