I would like to have two search inputs in searchform.php with two different submit buttons. One for searching through posts, the other one for categories. Depending on which input is filled, the search.php should display either post results, or category results.
How would I go about this? Do I need two different forms? How do I customise search.php as to display only the relevant results? Do I use a hidden field in the search form? I can handle displaying the results just fine, but how do I get $s
and, say, $s2
into search.php? I'm kinda lost as to where to start.
I would like to have two search inputs in searchform.php with two different submit buttons. One for searching through posts, the other one for categories. Depending on which input is filled, the search.php should display either post results, or category results.
How would I go about this? Do I need two different forms? How do I customise search.php as to display only the relevant results? Do I use a hidden field in the search form? I can handle displaying the results just fine, but how do I get $s
and, say, $s2
into search.php? I'm kinda lost as to where to start.
1 Answer
Reset to default 1For 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( '/' ) ); ?>">
<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="<?php bloginfo('template_url'); ?>/images/searchic.png" />
</button>
</form>
<form method="get" id="searchform2" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<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="<?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à!