0
votes

I am trying to get the product categories from woocommerce through a function in my wordpress theme and i have done this:

<?php
      $taxonomy     = 'product_cat';
      $orderby      = 'name';  
      $show_count   = 0;      // 1 for yes, 0 for no
      $pad_counts   = 0;      // 1 for yes, 0 for no
      $hierarchical = 1;      // 1 for yes, 0 for no  
      $title        = '';  
      $empty        = 0;
    $args = array(
      'taxonomy'     => $taxonomy,
      'orderby'      => $orderby,
      'show_count'   => $show_count,
      'pad_counts'   => $pad_counts,
      'hierarchical' => $hierarchical,
      'title_li'     => $title,
      'hide_empty'   => $empty
    );
    ?>
    <?php $all_categories = get_categories( $args );
    //print_r($all_categories);
    foreach ($all_categories as $cat) {
        //print_r($cat);
        if($cat->category_parent == 0) {
            $category_id = $cat->term_id;

    ?>      

    <?php       

            echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>'; ?>


            <?php
            $args2 = array(
              'taxonomy'     => $taxonomy,
              'child_of'     => 0,
              'parent'       => $category_id,
              'orderby'      => $orderby,
              'show_count'   => $show_count,
              'pad_counts'   => $pad_counts,
              'hierarchical' => $hierarchical,
              'title_li'     => $title,
              'hide_empty'   => $empty
            );
            $sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  $sub_category->name ;
                }

            } ?>



        <?php }     
    }
    ?>

This will list all the top level categories and subcategories under them hierarchically, but i have subcategories of subcategory(sub-sub-category), so how can i list those sub-sub-categories.

1

1 Answers

1
votes

The Easiest way would be to make a widget block by adding the following code in your function.php and drag/drop WooCommerce built-in "WooCommerce Product Categories" widget. It has some options to display categories/sub categories and sub sub categories.u

function arphabet_widgets_init() {

    register_sidebar( array(
    'name' => 'Widget Name',
    'id' => 'sidebar-1',
    'before_widget' => '<div class="your-class">',
    'after_widget' => '</div>',
) );

}    

Now create a sidebar file sidebar-1.php and in that file add the following code:

<?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : else : ?>    
<?php endif; ?>    

By uploading these files you will see a widget block option visible on your wordpress widget page. Include your sidebar-1.php file where you want your categories to appear and drag/drop *"WooCommerce Product Categories"** widget from wordpress widget section.

Thanks.