0

For a project I'm working on, I need two different searchforms. One is a global searchform that is always visible in the header of the page, that searches everything in the website. The other one however, only appears on a news page, and I need that one to only search for and display posts in the category "news".

I use the following code in search.php in order to have two unique searchforms, which is working like intended

if(isset($_GET['search-type'])) {
    $type = $_GET['search-type'];
    if($type == 'main') {
        load_template(TEMPLATEPATH . '/main-search.php');
    } elseif($type == 'news') {
        load_template(TEMPLATEPATH . '/news-search.php');
   }
}

And in functions.php I have this code, which displays 5 posts per page on the search results page which is working and what I want as well

function searchfilter($query) {
    if ($query->is_search()) {
        $query->set('posts_per_page', 5);
    }
    return $query;
}
add_filter('pre_get_posts', 'searchfilter');

However, for the second searchform, which is news-search.php, I need that one to only search in the category "news". I heard query_posts() is bad so I shouldn't be using that, but how else could I achieve this? I'm sorry if the answer is super easy or obvious, but I'm pretty new to Wordpress :) I've looked here on stackexchange and on google, but I'm having trouble putting it together to make it work. Any help would be greatly appreciated!

0

I heard query_posts() is bad so I shouldn't be using that, but how else could I achieve this?

Yes, query_posts is bad. You heard right. You are most of the way to doing this already. You have all the parts. You just need to mix them a little.

function searchfilter($query) {
    if ($query->is_search()) {
        $query->set('posts_per_page', 5);
        if(isset($_GET['search-type'])) {
             $type = $_GET['search-type'];
             if($type == 'news') {
                 $query->set('category_name','news'); // needs to be the slug not the name
             }
        }
    }
    return $query;
}
add_filter('pre_get_posts', 'searchfilter');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.