Trying to create function that displays the siblings and the first level children of the current product category. So not the children of the siblings or the children of the children.
The categories can go 4 levels deep, I need the list to change what it is displaying depending on the current page.
Example:
I found a few posts where displaying the siblings is explained, or the first level children. But I am trying to combine both, without success:
Get a list of siblings term ids from current product category in WooCommerce
Display current category first then child categories in WooCommerce
Any thought? Anything that would point me in the right direction would help.
After a lot of trial and error, I finally figured it out:
function wc_cat_menu() {
$queried_object = get_queried_object();
$taxonomy = 'product_cat';
$sibling_terms = get_terms( array(
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => $queried_object->parent
) );
echo '<ul>';
foreach( $sibling_terms as $sibling ) {
if ( $sibling->parent > 0 ) {
$sibling_id = $sibling->term_id;
$siblingChildren = get_terms( $taxonomy, array(
'parent' => $sibling_id,
'hide_empty' => false
) );
echo '<li><a href="' . get_term_link( $sibling ) . '">' . $sibling->name . '<span> (' . $sibling->count . ')</span></a>';
if( $siblingChildren ) {
echo '<ul>';
foreach ( $siblingChildren as $child ) {
echo '<li><a href="' . get_term_link( $child, $taxonomy ) . '">' . $child->name . '<span> (' . $child->count . ')</span></a></li>';
}
echo '</ul>';
}
echo '</li>';
}
}
echo '</ul>';
}
Learned a lot during the process! There is probably a much efficient way to achieve this, any suggestions are welcome.