WordPress.org

Ready to get started?Download WordPress

Forums

Searching Custom Taxonomies (2 posts)

  1. noelgreen
    Member
    Posted 2 years ago #

    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.

    <?php
    // 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
    </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!

  2. noelgreen
    Member
    Posted 2 years ago #

    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]

Topic Closed

This topic has been closed to new replies.

About this Topic