WORDPRESS - Oxygen - toolset

Display list of WooCommerce categories

Author: Aleš Sýkora, 19. 2. 2021

If you need to display list of all WooCommerce categories without products, you can use my code. It will display all categories with link to their archive page. It will also display category image, name of course and count of products inside the category.

It is all wrapped in HTML with OxyNinja framework applied. So if you are using it with Oxygen code block and OxyNinja, the result should look like this.

List of all WooCommerce categories with links
<div class="c-columns-5 c-columns-l-4 c-columns-m-2">
<?php
$children = get_categories( array(
    'taxonomy'     => 'product_cat',
    'orderby'      => 'name',
    'pad_counts'   => false,
    'hierarchical' => 1,
    'hide_empty'   => false
) );

if ($children) {
  foreach ($children as $subcat) :
    $catThumbnail_id = get_woocommerce_term_meta( $subcat->term_id, 'thumbnail_id', true );
    $catImage = wp_get_attachment_url( $catThumbnail_id );
    $catName = $subcat->name;
    $catDescription = $subcat->description;
    $catCount = $subcat->count;
    $catLink = esc_url(get_term_link($subcat, $subcat->taxonomy));
?>
<div class="c-padding-xs">
<div class="c-padding-xs c-card-light c-inline">
  <img class="c-round c-margin-right-s category-image" src="<?php echo $catImage; ?>">
	<a href="<?php echo $catLink ?>"><?php echo $catName . ' (' . $catCount . ')'; ?></a>
  </div>
  </div>
      <?php
 endforeach;
}
    ?>
</div>

If you want to display all categories on WooCommerce shop page and use this code in same template for product categories too, then you propably want to display only child categories. So you need to get the term of current archive page at first.

<div class="c-columns-5 c-columns-l-4 c-columns-m-2">
<?php
if ( is_shop() ) {  
  $children = get_categories( array(
    'taxonomy'     => 'product_cat',
    'orderby'      => 'name',
    'pad_counts'   => false,
    'hierarchical' => 1,
    'hide_empty'   => false
) );}
if ( is_product_category() ) {
$term = get_queried_object(); // Get current archive page
$children = get_terms($term->taxonomy, array(
  'parent'    => $term->term_id,
  'hide_empty' => false
));
}

if (isset($children)) {
  foreach ($children as $subcat) :
    $catThumbnail_id = get_woocommerce_term_meta( $subcat->term_id, 'thumbnail_id', true );
    $catImage = wp_get_attachment_url( $catThumbnail_id );
    $catName = $subcat->name;
    $catDescription = $subcat->description;
    $catCount = $subcat->count;
    $catLink = esc_url(get_term_link($subcat, $subcat->taxonomy));
?>
<div class="c-padding-xs">
<div class="c-padding-xs c-card-light c-inline">
  <img class="c-round c-margin-right-s category-image" src="<?php echo $catImage; ?>">
	<a href="<?php echo $catLink ?>"><?php echo $catName . ' (' . $catCount . ')'; ?></a>
  </div>
  </div>
      <?php
 endforeach;
}
    ?>
</div>