简体   繁体   中英

Display a dynamic WooCommerce siblings and direct children category list

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:

  • Category 1
  • Category 2
  • Category 3 <-- Current product category
    • Category 3-1
    • Category 3-2
    • Category 3-3
    • Category 3-4
  • Category 4
  • Category 5

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM