As I said in a comment above, setting query_var => false
for the custom taxonomy is not a solution because this will make term pages in frontend return a 404 error. Renounce to term pages in the frontend to make a simple form to work is far away to be a solution.
Finally I’ve solved the problem. Instead of set the name in the select element to ‘my_tax[]’, I’ve set it to something like ‘tax_input[‘my_tax’][]. Don’t ask me why WordPress needs this, but it fix the problem.
Just if someone needs an example.
My sample taxonomies:
$taxonomies = array(
'type' => array('label' => 'Types','slug' => 'type','hierarchical' => false,'multiple' => false),
'city' => array('label' => 'Cities','slug' => 'city','hierarchical' => true,'multiple' => false),
'community_features' => array('label' => 'Community features','slug' => 'community_features','hierarchical' => false,'multiple' => true),
'property_features' => array('label' => 'Property features','slug' => 'property_features','hierarchical' => false,'multiple' => true)
);
foreach($taxonomies as $taxonomy => $properties){
register_taxonomy(
$taxonomy,
'properties',
array(
'label' => __( $properties['label'] ),
'hierarchical' => $properties['hierarchical'],
'query_var' => true,
)
);
register_taxonomy_for_object_type( $taxonomy, 'properties' );
}
Here a sample form:
<form method="post" action="<?php echo get_post_type_archive_link('properties');?>">
<?php
foreach($taxonomies as $taxonomy) {
$args = array(
'show_option_all' => __('Select '.$taxonomy['label'],'properties'),
'orderby' => 'NAME',
'order' => 'ASC',
'hide_empty' => 0,
'echo' => 0,
'selected' => '',
'hierarchical' => true,
'name' => 'tax_input['.$taxonomy['slug'].'][]',
'class' => '',
'taxonomy' => $taxonomy['slug'],
);
if($taxonomy['multiple']){
$args['show_option_all'] = '';
}
$select = wp_dropdown_categories( $args );
if($taxonomy['multiple']){
$select = preg_replace("#<select([^>]*)>#", "<select$1 multiple>", $select);
}
echo $select;
}
?>
<input type="hidden" name="action" id="action" value="search">
<button type="submit"><?php _e('Search','properties');?></button>
</form>
Added a custom query var:
add_filter('query_vars', 'properties_add_query_vars');
function properties_add_query_vars( $vars) {
$vars[] = "action"; // name of the var as seen in the URL
return $vars;
}
An my sample pre_get_posts:
add_action( 'pre_get_posts', 'properties_pre_get_post' );
function properties_pre_get_post($query){
if(isset($query->query_vars['action']) && $query->query_vars['action'] == 'search'){
if($query->is_main_query() && !is_admin() && $query->is_archive ) {
$tax_query = array();
$tax_input = $_POST['tax_input'];
if(!empty($tax_input)){
foreach($tax_input as $key => $value){
if(array_key_exists($key, $taxonomies)){
if(!empty($value) && $value[0] != "0"){
$value = array_map('intval', $value);
$tax_query[] = array(
'taxonomy' => $key,
'field' => 'id',
'terms' => $value,
'operator' => 'AND'
);
}
}
}
$query->set('tax_query',$tax_query);
}
}
}
}