How to Modify WordPress Search Results on Specific Pages

css3 masonry layout

WordPress’s search functionality is a bit of a dark corner for me—I think because Google search makes every other form of search look a bit old-school and less exciting to learn deeply. But the advice in the linked article really helped me on a recent client project, where I needed the search form on one set of pages to only return posts from a specific category.

It turns out you can add custom fields to searchform.php to control what results it sends back, as in the following example from the linked article, limiting results to those in the post category with ID 5:

<form method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
    <input type="hidden" name="cat" id="cat" value="5" />
    <input type="text" size="16" name="s" value="Search"  />
    <input type="submit" value="Go" />
</form>

Add in WordPress’s awesome conditional tags, and you’ve got a very robust method of modifying the search form’s output depending on the current page’s post type, category, singular/not-singular status, and so on.

Thanks to WPExplorer for a great tutorial!


Add a Comment

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