Custom category search box for WordPress

I’ve seen plugins that add an additional drop down list of categories to the standard WordPress search bar, however this doesn’t really help me at all.

My site has a lot of posts in a lot of categories and what I want to do is add a large search box at the top of each category page titled ‘search [cat name]: ‘ this search box will only search the posts within the category they are currently looking at.

Read More

To save me having to place code (and create a category page template for each category I have) it would be brilliant if this can somehow be dynamically created. So what I am aiming to achieve is this:

  1. Dynamically created search bar title
  2. A search box that only searches within the category the user is currently viewing

I have this:

<form method="get" id="search form" action="/">
<div>
<input type="text" value="" name="s" id="s" />
<input type="hidden" value="22" name="cat" id="africa" />
<input type="submit" id="search_submit" name="Search" value="Search"/>
</div>
</form>

But it doesn’t seem to work, nor does it dynamically fill in the category ID which means i would have to create a new category template for each category I have.

It’ll be very much appreciated if anybody could help me with this, thanks.

Related posts

1 comment

  1. In every template file of your theme, even in the header.php you can put

    <?php
    $term = null;
    $btn = __('Search');
    if ( is_category() ) { $term = get_queried_object(); }
    ?>
    <form method="get" id="search_form" action="<?php echo home_url(); ?>">
    <div>
    <input type="text" value="" name="s" id="s" />
    <?php
    if ($term) {
      $btn = sprintf( __('Search in %s'), $term->name);
    ?>
    <input type="hidden" value="<?php echo $term->term_id; ?>" name="cat" />
    <input type="hidden" value="<?php echo $term->name; ?>" name="catname" />
    <?php } ?>
    <input type="submit" id="search_submit" name="Search" value="<?php echo $btn; ?>"/>
    </div>
    </form>
    

    If you are viewing a category it will show a category restricted search, in other cases it show a generic search form.

    Then in your search.php, to dinamically output the title put something like:

    <?php
    $searchtitle = isset($_GET['catname']) && ! empty($_GET['catname']) ? 
    sprintf( __('Search Results for &quot;%s&quot; in category &quot;%s&quot;'), $_GET['s'], $_GET['catname']) :
    sprintf( __('Search Results for &quot;%s&quot;'), $_GET['s']);
    ?>
    <h1><?php echo $searchtitle; ?></h1>
    

Comments are closed.