How do I modify a search query in WordPress?

I am using WordPress and have a search box in the header. It searches on the basis of posts. Now I want to modify this search box with a cities drop down search box. I also added a new cities table in the database. I need to run the search box on the basis of cities.

Related posts

Leave a Reply

2 comments

  1. You can simply add following code in your functions.php file in your WordPress theme directory.

    function searchfilter($query) {
    
    if ($query->is_search && !is_admin() ) {
        $query->set('post_type',array('trip'));
    }
    
    return $query;
    }
    
    add_filter('pre_get_posts','searchfilter');
    

    Here trip is my custom post type and now default search function of WordPress will only search in custom post type trip.
    You can modify it according to your requirements.

  2. If you have made a special table for locations you are probably going to need your own search query and start from that one to develop your needs.

    A good start would be to create a new template file to which you are going to submit your search form, and a search function in functions.php which is a mandatory file in your theme.

    A good example on how to do that I found in Search Multiple Custom Fields in WordPress.

    However, you might ask: Why do you need to write a special search function for that? You said you have added a new table in the database that is not part of the default taxonomy system of WordPress so that one is not going to take into consideration your extra parameters of the search.

    Moreover I do not recommend you to modify the core search function, because at some particular time you would probably like to make an upgrade or so, and that is going to mess up with your search. The functions.php file way is the safer way and yields results faster.