1

New2Tip: Allow Visitors To Search By Category

Learn how to easily add a category drop down select box to your WordPress search form to provide a more customizable way to search for a specific post on your site....
New2Tip: Allow Visitors To Search By Category

Changing The Form

To add the drop down select menu for categories, you simply use the wp_dropdown_categories() function with at least one parameter of show_option_none=Select category. You can also add other options too if you like.

The following code is what I use for the searchform.php here on New2WP.

<!-- The searchform.php template code -->
<form id="searchform" method="get" action="<?php bloginfo('url'); ?>">
    <input type="text" name="s" id="s" size="15" />
    <?php wp_dropdown_categories('show_option_none=Select category'); ?>
		<input name="s" id="s" type="text" class="searchinput" value="<?php if ( is_search() ) echo esc_attr( get_search_query() ); else echo 'Search'; ?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;" />
    <input type="submit" value="Search" />
</form>

Add a function

In order to hook into the search query that happens when you submit the search form you need to add this to your functions.php file.

// Add to functions.php file.
add_action('pre_get_posts', 'search_by_cat');

function search_by_cat() {
	global $wp_query;

	if (is_search()) {
                $cat = intval( $_GET['cat'] );
                $cat = ( $cat > 0  ) ? $cat : '';
                $wp_query->query_vars['cat'] = $cat;
    }
}

If you have any questions about this please post a comment below and let me know. This is something that is so easy though, that it took me just about 10 minutes to add to New2WP on all pages besides the homepage. It shouldn't be too difficult to figure out, but let me know if you need help I'm happy to help with anything.

Shortlink:

Get automatic updates! Subscribe to Our RSS Feed or Get Email Updates sent straight to your inbox!

About the Author

Jared is from Boston working as a web and graphic designer. Also owns the design blog Tweeaks.com, and has designed many other websites powered by Wordpress including the New2WP theme.

Level: Noob

User Comments

( ADD YOURS )

  1. Another great tip! Thanks. One more Q ( again:) ). How could one add beside category search, custom taxonomy search too? IE: One could have custom taxonomy Music and in it there could be numerous hierarchical taxonomy terms such as Rock, POP, Techno, Classic and such.

    So our advanced search dropdown could look like this:

    Categorys:
    - Blog
    - News
    - Archive
    Music:
    - Rock
    - Classic
    - Techno
    - Pop

    Cheers and thank you!

Trackbacks


  1. Avatar

    Your Name
    February 4


    CommentLuv badge