When you use wp_list_categories()
you get a list of terms, each one linked to its archive page. I think what you need is a form to filter the products, not a list of archive term links, so you can keep the selected filters between requests, for example, using $_POST
, $_SESSION
or $_COOKIES
.
Example using $_POST
:
<?php
//taxonomies you want to filter
$taxonomies = array( "countries", "types" );
function get_terms_dropdown($taxonomy, $args){
$terms = get_terms($taxonomy, $args);
$output="<select id="".$taxonomy.'" name="'.$args['name'].'" multiple>';
foreach($terms as $term){
in_array($term->term_id, $args['selected']) ? $sel=" selected" : $sel="";
$output .='<option value="'.$term->term_id.'"'.$sel.'>'.$term->name.'</option>';
}
$output .="</select>";
return $output;
}
?>
<?php
//Set the action of the from to custom post type archive
?>
<form method="post" action="<?php echo get_post_type_archive_link('products');?>" id="products-filter-form">
<?php
foreach($taxonomies as $taxonomy) {
//check if there is a previously selected terms
$selected = (!empty($_POST['tax_input'][$taxonomy])) ? ($_POST['tax_input'][$taxonomy]) : array();
$selected = array_map('intval', $selected);
$args = array(
'hide_empty' => false,
'selected' => $selected,
'name' => 'tax_input['.$taxonomy.'][]',
);
echo get_terms_dropdown($taxonomy,$args);
}
?>
<button type="submit">Filter</button>
<button type="reset" value="reset">Reset</button>
</form>
And now the in the preg_get_posts action you add the selected taxonomy terms to the query:
add_action( 'pre_get_posts', 'cyb_pre_get_post' );
function cyb_pre_get_post($query){
if($query->is_main_query() && !is_admin() && is_post_type_archive( 'products' ) ) {
//taxonomies you want to filter
$taxonomies = array( "countries", "types" );
$tax_input = isset($_POST['tax_input']) ? $_POST['tax_input'] : '';
if(!empty($tax_input)){
//Ready to construct the tax_query
foreach($taxonomies as $taxonomy) {
if(isset($tax_input[$taxonomy])) {
$value = array_map('intval', $tax_input[$taxonomy]);
if(!empty($value) && $value[0] != "0"){
$tax_query[] = array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $value
);
}
}
}
$query->set('tax_query',$tax_query);
//The tax_query has been set
}
}
}
Note: code tested with category
and post_tag
taxonomies and it is working. It may need some modifications to fully fit your needs.