Skip to content

Instantly share code, notes, and snippets.

@jorpdesigns
Last active July 26, 2021 16:32
Show Gist options
  • Save jorpdesigns/f717e1810a6ae7e3cbf6fd97a42574b6 to your computer and use it in GitHub Desktop.
Save jorpdesigns/f717e1810a6ae7e3cbf6fd97a42574b6 to your computer and use it in GitHub Desktop.
Shortcode to display subcategories under a WooCommerce parent category
<?php
// Shortcode example: [display_subcats id="55"]. Replace 55 with your parent category ID
add_shortcode('display_subcats', 'display_subcats');
function display_subcats( $atts, $content = null ) {
$atts = shortcode_atts(
array(
'id' => ''
), $atts);
ob_start();
echo '<div class="categories-wrapper">';
// Other query args available here: https://developer.wordpress.org/reference/classes/wp_term_query/__construct/
$args = array(
'hide_empty' => false,
'show_option_none' => '',
'child_of' => $atts['id'],
'taxonomy' => 'product_cat'
);
$subCategories = get_categories($args);
foreach ($subCategories as $category) {
// Other category info available here: https://developer.wordpress.org/reference/functions/get_terms/#comment-1839
$categoryName = $category->name;
$thumbnail_id = get_term_meta( $category->term_id, 'thumbnail_id', true);
$categoryImage = wp_get_attachment_image($thumbnail_id, $size = 'full');
$categoryLink = get_term_link( $category->slug, $category->taxonomy );
echo '<div class="category-box-wrapper">';
echo '<div class="category-image"><a href="' . $categoryLink . '">' . $categoryImage . '</a></div>';
echo '<h5 class="category-link"><a href="' . $categoryLink . '">' . $categoryName . '</a></h5>';
echo '</div>';
}
echo '</div>';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment