Last active
July 26, 2021 16:32
-
-
Save jorpdesigns/f717e1810a6ae7e3cbf6fd97a42574b6 to your computer and use it in GitHub Desktop.
Shortcode to display subcategories under a WooCommerce parent category
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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