I am trying to query woocommerce product categories but only those which have on sale products. Is there any possibilities? The result is hierarchy parent > child. I want to show both parent and its child. i.e. if child has product on sale print the parent category as well.
Here is the code I wrote so far
<ul class="accordion list-group sub-catalog">
<?php $terms = get_terms('product_cat', array( 'parent' => 0, 'exclude' => '15' ));
if( $terms ):
$original_query = $wp_query;
foreach ( $terms as $key => $term ):
$child = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
?>
<li class="accordion-card list-group-item">
<div class="acc-card-title">
<a href="<?php echo get_term_link($term); //echo $term->name; ?>"><?php echo $term->name; ?></a>
<?php if ( ! $child ){ ?>
<?php
} else {
?>
<span class="fa fa-plus"></span>
<?php
}
?>
</div>
<ul class="accordion list-group sub-catalog">
<?php
$child_terms = get_terms(
'product_cat',
array(
'child_of' => $term->term_id,
'hide_empty' => true
)
);
foreach ( $child_terms as $child_term ) {
$re_child_terms = get_terms(
'product_cat',
array(
'child_of' => $child_term->term_id,
'hide_empty' => true
)
);
if ( ! $re_child_terms ){
?>
<li class="accordion-card list-group-item">
<div class="acc-card-title">
<a href="<?php echo get_term_link($child_term);?>"> <?php echo $child_term->name; ?></a>
</div>
</li>
<?php
}
}
?>
</ul>
</li>
<?php
endforeach;
$wp_query = null;
$wp_query = $original_query;
?>
</ul>
<?php endif; ?>
Thanks in advance.
2
Answers
this is how I get the on sale products and get their category name . where to use array_diff function
The code below solved the problem.