Skip to content

Instantly share code, notes, and snippets.

@delennerd
Last active December 5, 2021 21:09
WooCommerce - Display subcategories on category page (set category as default shop page)
<?php
add_action( 'woocommerce_after_subcategory', 'dlm_display_subcategories_on_category', 12 );
function dlm_display_subcategories_on_category( $category )
{
$cat_id = $category->term_id;
$taxonomy = 'product_cat';
// Get subcategories of the current category
$terms = get_terms([
'taxonomy' => $taxonomy,
'hide_empty' => false,
'parent' => $cat_id,
'pad_counts' => 1,
]);
// echo '<pre>'; print_r($terms); echo '</pre>';
$output = '<ul class="subcategories-list">';
// Loop through product subcategories WP_Term Objects
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $taxonomy );
$countItemsText = sprintf(
'(%1$s %2$s)',
$term->count,
__( 'Products', 'dlm_wp_theme' ),
);
$output .= '<li class="subcategory-slug-'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .' '. $countItemsText .'</a></li>';
}
echo $output . '</ul>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment