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).

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.


Leave a Reply

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