This is a function that generates a shortcode that can be used in products archive template to display the subcategories of the current queried category if any. You can style the output as you wish.
/* !Function that generates a shortcode to display the subcategories of a category */
add_shortcode('subcategories_list', 'subcategories_shortcode');
function subcategories_shortcode() {
if ( !is_product_category() ) {
return ''; // Ensure the function only runs on product category pages
}
// Get the current product category
$current_category = get_queried_object();
// Get subcategories of the current category
$subcategories = get_terms([
'taxonomy' => 'product_cat',
'parent' => $current_category->term_id,
'hide_empty' => true, // Set to true if you want to exclude empty categories
'orderby' => 'menu_order', // Follow the order from the admin
'order' => 'ASC', // Default sorting order
]);
if ( empty( $subcategories ) || is_wp_error( $subcategories ) ) {
return ''; // Handle cases where there are no subcategories
}
// Start output buffer
ob_start();
echo '<div class="subcategories-wrapper">';
foreach ($subcategories as $subcategory) {
// Get subcategory thumbnail
$thumbnail_id = get_term_meta($subcategory->term_id, 'thumbnail_id', true);
$thumbnail_url = $thumbnail_id ? wp_get_attachment_url($thumbnail_id) : wc_placeholder_img_src();
// Get subcategory name and product count
$name = $subcategory->name;
$product_count = $subcategory->count;
// Subcategory URL
$subcategory_link = get_term_link($subcategory);
// Render subcategory HTML
echo '<div class="subcategory-item">';
echo '<a href="' . esc_url($subcategory_link) . '">';
echo '<img src="' . esc_url($thumbnail_url) . '" alt="' . esc_attr($name) . '" />';
echo '<div>';
echo '<h3>' . esc_html($name) . '<mark class="count">(' . $product_count . ')</mark></h3>';
echo '</div>';
echo '</a>';
echo '</div>';
}
echo '</div>';
// Return output
return ob_get_clean();
}
Code language: PHP (php)