Skip to content

Instantly share code, notes, and snippets.

@braddalton
Last active July 29, 2024 20:39
Show Gist options
  • Save braddalton/c606356439192ef0b791792ef44594a9 to your computer and use it in GitHub Desktop.
Save braddalton/c606356439192ef0b791792ef44594a9 to your computer and use it in GitHub Desktop.
WooCommerce Child Categories on Parent Category Archive Page
// Hook into the WooCommerce before shop loop to display subcategories
add_action('woocommerce_before_shop_loop', 'display_woo_subcategories', 15);
function display_woo_subcategories() {
if (!is_product_category()) {
return;
}
$term_id = get_queried_object_id();
$taxonomy_name = 'product_cat';
$termchildren = get_term_children($term_id, $taxonomy_name);
if (empty($termchildren)) {
return;
}
echo '<div class="woo-subcategories multi-column">';
echo '<ul>';
foreach ($termchildren as $child) {
$term = get_term_by('id', $child, $taxonomy_name);
$thumbnail_id = get_term_meta($term->term_id, 'thumbnail_id', true);
$image = wp_get_attachment_url($thumbnail_id);
echo '<li>';
echo '<a href="' . esc_url(get_term_link($term, $taxonomy_name)) . '">';
if ($image) {
echo '<img src="' . esc_url($image) . '" alt="' . esc_attr($term->name) . '" />';
}
echo '<h3>' . esc_html($term->name) . '</h3>';
echo '</a>';
echo '</li>';
}
echo '</ul>';
echo '</div>';
}
.woo-subcategories.multi-column ul {
display: flex;
flex-wrap: wrap;
list-style: none;
padding: 0;
margin: 0;
}
.woo-subcategories.multi-column ul li {
flex: 1 1 30%;
box-sizing: border-box;
text-align: center;
}
.woo-subcategories.multi-column ul li img {
max-width: 100%;
height: auto;
display: block;
margin: 0 auto 10px;
}
.woo-subcategories.multi-column ul li h3 {
margin: 0;
font-size: 16px;
line-height: 1.5;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment