I've create a page template page-products.php which displays all the products (custom post type "product"). You can see the page on this url: http://axces-staging.houston-1.hybridmedia.be/producten/
On the left side of the page you have to filter. These are the taxonomy terms for the custom post type "product".
<?php
$args = array('hide_empty' => false, 'orderby' => 'term_group', 'parent' => false);
$terms = get_terms('product_categorie', $args);
$hierarchy = _get_term_hierarchy('product_categorie');
echo '<ul class="filter">';
foreach ($terms as $term) {
echo '<li class="parent"><strong class="parent__item">'.$term->name.'</strong>';
if (array_key_exists($term->term_id, $hierarchy)) {
echo '<ul class="childs">';
foreach ($hierarchy[$term->term_id] as $v) {
$child = get_term($v);
echo '<li class="child" data-filter="'.$child->slug.'">'.$child->name.'</li>';
}
echo '</ul>';
}
echo '</li>';
}
echo '</ul>';
?>
All the products are shown with this code:
<?php $args = array('post_type' => 'product'); ?>
<?php $loop = new WP_Query($args); ?>
<?php if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php get_template_part( 'loop-templates/content-product' ); ?>
<?php endwhile; ?>
<?php else: ?>
<h1>
<?php _e('Geen producten gevonden','axces-theme'); ?>
</h1>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
But how am I able to change the product query depending on the clicked child term? So if I click on the term "Wandlezers" for example, I want to show only the products with the term "Wandlezers".
Add a term link in your code like
<?php
$args = array('hide_empty' => false, 'orderby' => 'term_group', 'parent' => false);
$terms = get_terms('product_cat', $args);
$hierarchy = _get_term_hierarchy('product_cat');
echo '<ul class="filter">';
foreach ($terms as $term) {
echo '<li class="parent"><strong class="parent__item">'.$term->name.'</strong>';
if (array_key_exists($term->term_id, $hierarchy)) {
echo '<ul class="childs">';
foreach ($hierarchy[$term->term_id] as $v) {
$child = get_term($v);
echo '<li class="child" data-filter="'.$child->slug.'"><a href="?product_cat=' . $term->term_id. '">'.$child->name.'</a></li>';
}
echo '</ul>';
}
echo '</li>';
}
echo '</ul>';
?>
Then change your loop query args like this
<?php
$args = array(
'post_type' => 'product',
'post_status' => 'any'
);
if ( ! empty( $_GET['product_cat'] ) ) {
$args['tax_query'] = array(
array(
'taxonomy' => 'product_cat',
'field' => 'id',
'terms' => $_GET['product_cat'],
),
);
}
?>
<?php $loop = new WP_Query($args); ?>
<?php if ( $loop->have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php get_template_part( 'loop-templates/content-product' ); ?>
<?php endwhile; ?>
<?php else: ?>
<h1>
<?php _e('Geen producten gevonden','axces-theme'); ?>
</h1>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
I hope it will work for you.