Limit the Search result to only POSTS

Arshad
13 Dec 2022

In WordPress, when you use the search form to search something, the result page contains POSTS and PAGES by default if it is Default WP_QUERY. Sometimes we don’t need Pages to be shown in search results or we need some Custom Post Type also to be included there.

Here is a code-snippet for that. Implementation is easy. I prefer Scripts Organizer.

Steps to implement :

  1. Add a code-block in Scripts Organizer and name it as you like.
  2. Set trigger location to EVERYWHERE and scripts location to PHP.
  3. put the code there and click update.
  4. You are good to go.
<?php

function limited_search_filter($query) {
    if ($query->is_search() && $query->is_main_query() && !is_admin()) {
        $query->set('post_type', array('post')); //Limit to POSTS only
    }
    return $query;
}

add_filter('pre_get_posts', 'limited_search_filter');

or if you want to include any CPT also to the search result you can use below function instead.

<?php

function extended_search_filter($query) {
    if ($query->is_search() && $query->is_main_query() && !is_admin()) {
        $query->set('post_type', array('post', 'CPT_SLUG'));
        //change CPT_SLUG to your CPT slug, like testimonials, reviews, products etc.
    }
    return $query;
}

add_filter('pre_get_posts', 'extended_search_filter');

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy