Back to all posts

Customizing and Modifying WordPress Search Results and Query


Modifying the search result query in WordPress can be done by using the `pre_get_posts` filter to alter the query arguments before the search result query in WordPress

Add the following code to the functions.php file.

function modify_search_query($query) {
    if ($query->is_search && !is_admin()) {
        // Modify the search query arguments here
        $query->set('posts_per_page', 10);
        $query->set('post_type', 'post');
    }
    return $query;
}

add_filter('pre_get_posts', 'modify_search_query');

Customize the search query arguments: Inside the ‘modify_search_query’ function, you can customize the search query arguments as needed.

If you want add custom post type in search query so just add following code.

function search_filter($query) {
    if ($query->is_search && !is_admin()) {
        // Add custom post types to search query
        $query->set('post_type', array('post', 'custom_post_type'));
    }
    return $query;
}

add_filter('pre_get_posts', 'search_filter');