Modifying WP Query for Advance Search in WordPress

Many times you may want to restrict your WordPress site’s search result to particular custom post, category, taxonomy or author. You may even wish to exclude some pages and posts from the search result.
The following code will allow you to do that by modifying WP Query. Put this code in your theme’s functions.php file
(found in [directory_containing_wordpress_files]/wp-content/themes/[active_theme]/functions.php).

function modify_search_query($query) {

    /*
     * Check if the query fired is a search query
     */
    if (!$query->is_search) {
        return $query;
    }

    /*
     * Show post from particular author
     */
    $query->set('author_name', 'test');

    /*
     * Search in posts, pages and custom post movies
     */
    $query->set('post_type',array('post','page','movies'));

    /*
     * Show results only from particular categories in this case ones with id 8 and 9
     */
    $query->set('category__in',array(8,9));

    /*
     * Search only in particular taxonomy terms
     */
    $query->set('tax_query',array(
									array(
										'taxonomy' => 'genre',
										'field' => 'slug',
										'terms' => 'bob'
									)
								)
    			);

    /*
     * Exclude certains posts
     */
    $query->set('post__not_in',array(5,6));

    return $query;

}

/*
 * WordPress filter that does the magic
 */
add_filter('pre_get_posts','modify_search_query');

Here the key function is add_filter(‘pre_get_posts’,’modify_search_query’) which is a wordpress hook that runs before the query runs. This filter gives the developer the option to access the $query object by reference. Thus by modifying Wp query object we are filtering our search result.

Reference

http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts

Leave a Reply

Your email address will not be published. Required fields are marked *