Support » Fixing WordPress » Searching Custom Taxonomies

  • I have a site that I have many custom taxonomies on — Home, Body, Food, Kids, Pets, and Community — and needed a search to be able to search only within those areas. That didn’t take me long to figure out how to do with a hidden field, but I had a different search field for every page.

    I wanted one search form template that could be used everywhere and would know what it should search… if you were within a taxonomy, it would search just that, if you were on the main page it would search everything.

    So… this is what I came up with and it works so beautifully I thought I’d share.

    // first we get the slug, the term and the taxonomy name.
    $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
    // now we enter in the normal search form parameters
    <form method="get" id="yourstyle" action="<?php bloginfo('url'); ?>/">
    // create the text field
    <input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
    // create the submit button and populate it with a list of all the taxonomy terms that we have.  if it matches any of those then it adds that taxonomies slug to the search field as well, if not it adds nothing.
    <input type="submit" value="Search <?php if ($term->slug == 'home' || 'body' || 'food' || 'kids' || 'pets' || 'community' ) { echo "$term->slug"; } else { echo ""; } ?> »" />
    // now we create a hidden field and do the same thing it we did with our submit button. if the page is in any of our taxonomies then it echos that to the "name" and "value" parameters. note that the "name" gets the "term slug" (all lowercase) and the "value" gets the "term name" (initial cap).
    <input type="hidden" name="<?php if ($term->slug == 'home' || 'body' || 'food' || 'kids' || 'pets' || 'community' ) { echo "greenmy_$term->slug"; } else { echo ""; } ?>" value="<?php echo $term->name; ?>" />
    // close our form

    That’s it! Now the page will search in a taxonomy only if you’re on a taxonomy page, otherwise it will search everything.

    Hope this helps others!

Viewing 1 replies (of 1 total)
  • Update on this is for if you want to do it with just categories… you could do something like this.

    [32 lines of code moderated as per the Forum Rules. The maximum number of lines of code that you can post in these forums is ten lines. Please use the pastebin]

Viewing 1 replies (of 1 total)
  • The topic ‘Searching Custom Taxonomies’ is closed to new replies.