Modifying searchform.php and search.php to have two kinds of searches

For anyone trying to achieve something similar, here’s how I solved it:

In searchform.php, duplicate the form, as such:

<form method="get" id="searchform" action="<?php echo esc_url( home_url( "https://wordpress.stackexchange.com/" ) ); ?>">
    <input type="text" name="s" id="s" placeholder="<?php esc_attr_e( 'Search by Post' ); ?>" />
    <input type="hidden" name="search-type" value="posts" />
    <button type="submit" name="submit" id="searchsubmit" value="<?php esc_attr_e( 'Search' ); ?>">
    <img src="https://wordpress.stackexchange.com/questions/239760/<?php bloginfo("template_url'); ?>/images/searchic.png" />
    </button>
</form>
<form method="get" id="searchform2" action="<?php echo esc_url( home_url( "https://wordpress.stackexchange.com/" ) ); ?>">
    <input type="text" name="s" id="s2" placeholder="<?php esc_attr_e( 'Search by Category' ); ?>" />
    <input type="hidden" name="search-type" value="categories" />
    <button type="submit" name="submit" id="searchsubmit2" value="<?php esc_attr_e( 'Search' ); ?>">
    <img src="https://wordpress.stackexchange.com/questions/239760/<?php bloginfo("template_url'); ?>/images/searchic.png" />
    </button>
</form>

Then in search.php, below get_header(), the following:

if(isset($_GET['search-type'])) {
    $searchtype = $_GET['search-type'];
    if($searchtype == 'posts') {
        get_template_part( 'search', 'posts' );
    } elseif($searchtype == 'categories') {
        get_template_part( 'search', 'categories' );
    }
}

Then make two files, “search-posts.php” and “search-categories.php” where you can define the loops of the respective search results.

VoilĂ !

Leave a Comment