Search form with custom taxonomy terms and categories

June 4, 2010 | Wordpress tutorials | 7 Comments »

Today I’ll show you how to make custom search form, where you could select taxonomy term or category or maybe both.

Final result:

Firstly you should go to your themes directory and create new folder, for example lib. In lib folder create a file dropdown.php and paste code below:

<?php
// drop down menu for search
function dropdown_search($taxonomy, $args = '' ) {
	$defaults = array('taxonomy' => 'my_taxonomy', // <- write taxonomy name
		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC',
		'exclude' => '', 'include' => ''
	);
	$args = wp_parse_args( $args, $defaults );

	$terms = get_terms($taxonomy, array_merge($args, array('orderby' => 'count', 'order' => 'DESC')) ); // Always query top tags

	if ( empty($terms) )
		return;

	$return = generate_dropdown_search( $terms, $taxonomy, $args ); // Here's where those top tags get sorted according to $args
	if ( is_wp_error( $return ) )
		return false;
	else
		echo apply_filters( 'dropdown_search', $return, $args );
}

function generate_dropdown_search( $terms, $taxonomy, $args = '' ) {
	global $wp_rewrite;
	$defaults = array(
		'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45,
		'format' => 'flat', 'orderby' => 'name', 'order' => 'ASC'
	);
	$args = wp_parse_args( $args, $defaults );
	extract($args);

	if ( !$terms )
		return;
	$counts = $term_links = $term_slugs = array();
	foreach ( (array) $terms as $term ) {
		$counts[$term->name] = $term->count;
		$term_links[$term->name] = get_term_link( $term->name, $taxonomy );
		$term_slugs[$term->name] = $term->slug;
		if ( is_wp_error( $term_links[$term->name] ) )
			return $term_links[$term->name];
		$term_ids[$term->name] = $term->term_id;
	}

	$min_count = min($counts);
	$spread = max($counts) - $min_count;
	if ( $spread <= 0 )
		$spread = 1;
	$font_spread = $largest - $smallest;
	if ( $font_spread <= 0 )
		$font_spread = 1;
	$font_step = $font_spread / $spread;

	// SQL cannot save you; this is a second (potentially different) sort on a subset of data.
	if ( 'name' == $orderby )
		uksort($counts, 'strnatcasecmp');
	else
		asort($counts);

	if ( 'DESC' == $order )
		$counts = array_reverse( $counts, true );

	$a = array();

	$rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? ' rel="term"' : '';

	foreach ( $counts as $term => $count ) {
		$term_id = $term_ids[$term];
		$term_link = clean_url($term_links[$term]);
		$term_slug = $term_slugs[$term];
		$term = str_replace(' ', '&nbsp;', wp_specialchars( $term ));
		$a[] = "\t<option value='$term_slug'>$term ($count)</option>";
	}

	switch ( $format ) :
	case 'array' :
		$return =& $a;
		break;
	case 'list' :
		$return = "<ul class='wp-tag-cloud'>\n\t<li>";
		$return .= join("</li>\n\t<li>", $a);
		$return .= "</li>\n</ul>\n";
		break;
	default :
		$return = join("\n", $a);
		break;
	endswitch;

	return apply_filters( 'generate_dropdown_search', $return, $term, $args );
}
?>

Edit line 4th and save.


Open functions.php file and write after opening php tag:

define('THEMELIB', TEMPLATEPATH . '/lib');

require_once(THEMELIB . '/dropdown.php');

Now you should create a new file in theme directory for example custom-search.php and paste code below:

<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div class="alignleft">
<?php wp_dropdown_categories( 'show_option_all=Select...' ); ?>
<select name="taxonomy">
<option value="0">Select...</option>
<?php dropdown_search('my_taxonomy', 'number=0&order=asc'); ?>
</select>
</div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" class="searchinput" />
<input type="submit" id="searchsubmit" value="Search" class="btn" />
</form>

Finally you can call newly created search form like this:

<?php include (TEMPLATEPATH . '/custom-search.php'); ?>

Pingbacks & Trackbacks

  1. [...] has a good article here about searching custom taxonomies and catagories together…  good place to start at least… This entry was posted in web. Bookmark the [...]

7 Responses

  1. Tom Buckley says:

    Thanks for the tutorial, there is very little information on searching and filtering custom taxonomies available so this is a big help.

    One thing I would really like to be able to do would be to have mulitple drill-down select boxes for heirahical taxonomies with keyword search. E.g. Search for jobs by ‘keyword’, taxonomny_term = “region” , taxonomy_term=’country’ , taxonomy_term = ’state’ etc etc…

  2. Hello,
    Thanks for this great tutorial.

    I want to ask you. What if we have more than 1 taxonomy?

  3. Morfo says:

    Can we use this search engine for custom-post-type or its work only with articles
    if it is possible how?

    thank you :)

  4. JesperA says:

    Hi!

    The thought behind this is really awesome, but the problem is that it doesnt work for me.

    I changed the “my_taxonomy” to “location”, it lists every taxonomy within the “location”, the problem is that this function outputs the wrong string for me, it outputs “?cat=0&taxonomy=dalarna&s=”, it should be outputting “?cat=0&taxonomy=location&term=dalarna&s”, do you know how to fix that?

    Would really appreciate it

  5. Years Later…
    The answer to having multiple dropdowns searching different taxonomies is this:
    In the function, Change ‘my_taxonomy’ to $taxonomy

    Then duplicate your and change the taxonomy name in each to pass to the function.

Leave a Reply