I am trying to build an advanced search form that allows users to select from two taxonomy based drop down menus. Each taxonomy drop down has taxonomy terms from which the user can select multiple terms. When they make their selections they should be forwarded to a search results page that queries and displays matching results. I tried adapting from this post: http://fearlessflyer.com/how-to-create-an-advanced-search-form-for-wordpress/.
I have a custom post type named "recipe" with two taxonomies named "Meal Types" and "Cuisines". The taxonomies have the following terms:
Meal Types
- Dinner
- Breakfast
Cuisines
- French
- American
The below code works fine when one selects Dinner and American or Breakfast and French, but not when one selects more than one term in a taxonomy drop down. Logically speaking, when one selects and submits French and American, posts that have either French or American should display. However it is not working. It should function like the following advanced search:http://cooking.nytimes.com/search?
I think the problem is related to the fact that I am unable to figure out how to submit multiple taxonomy terms to the search page via $_POST so that they can then be queried and displayed on the results page.
Thanks!
functions.php
function buildSelect($tax){
$terms = get_terms($tax);
$x = '<select multiple="multiple" name="'. $tax .'">';
$x .= '<option value="">Select '. ucfirst($tax) .'</option>';
foreach ($terms as $term) {
$x .= '<option value="' . $term->slug . '">' . $term->name . '</option>';
}
$x .= '</select>';
return $x;
}
homepage
<form method="post" action="<?php bloginfo('url');?>/listing-search-results/">
<?php $taxonomies = get_object_taxonomies('recipe');
foreach($taxonomies as $tax){
echo buildSelect($tax);
}
?>
<input type="submit"/>
</form>
Search Results Page
<?php
$list = array();
$item = array();
foreach($_POST as $key => $value){
if($value != ''){
$item['taxonomy'] = htmlspecialchars($key);
$item['terms'] = htmlspecialchars($value);
$item['field'] = 'slug';
$list[] = $item;
}
}
$cleanArray = array_merge(array('relation' => 'AND'), $list);
$args['post_type'] = 'recipe';
$args['showposts'] = 9;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args['paged'] = $paged;
$args['tax_query'] = $cleanArray;
$the_query = new WP_Query( $args );
?>
<?php echo ($the_query->found_posts > 0) ? '<h3 class="foundPosts">' . $the_query->found_posts. ' listings found</h3>' : '<h3 class="foundPosts">We found no results</h3>';?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post();?>
//add our code here i.e. the_title();
<?php endwhile; wp_reset_postdata();?>
<div class="row page-navigation">
<?php next_posts_link('« Older Entries', $the_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries »') ?>
</div>