Created
November 7, 2021 12:45
-
-
Save bencicpatricija/dcb7ddcd86c840ce147412d9d40171f6 to your computer and use it in GitHub Desktop.
WooCommerce product category list with child categories
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 | |
/** | |
* WooCommerce product category list with child categories | |
*/ | |
// Function to get top-level "product_cat" terms with their child terms (1 level only). | |
function pb_get_woocommerce_categories() { | |
$taxonomy = 'product_cat'; | |
// If you wish to exclude "Uncategorized" term ID, use this function - https://gist.github.com/bencicpatricija/3eec5e8345202c7b06d4838219dff112 | |
$exclude = pb_get_product_uncategorized_term_id() | |
// Get top-level "Product category" terms. | |
$categories = get_terms([ | |
'taxonomy' => $taxonomy, | |
// 'exclude' => $exclude, | |
'parent' => 0, | |
]); | |
foreach ( $categories as $cat ) { | |
// Create an array with top-level parent category's term as an array key. | |
$cat_array[$cat->term_id] = []; | |
// Get current top-level parent category's child terms. | |
$child_categories = get_terms([ | |
'taxonomy' => $taxonomy, | |
'parent' => $cat->term_id, | |
'hide_empty' => false, | |
]); | |
$sub_cat_array = []; | |
foreach ( $child_categories as $child_cat ) { | |
// Create an array with child category's term IDs. | |
$sub_cat_array[] = $child_cat->term_id; | |
} | |
// Push array of child categories to previously created parent category's array. | |
$cat_array[$cat->term_id] = $sub_cat_array; | |
} | |
return $cat_array; | |
} | |
// Example usage. | |
$categories = pb_get_woocommerce_categories(); | |
foreach ( $categories as $parent_cat => $child_cats ) : ?> | |
<h2><?php echo get_term( $parent_cat )->name; ?></h2> | |
<ul> | |
<?php foreach ( $child_cats as $sub_cat ) : ?> | |
<li><?php echo get_term( $sub_cat )->name; ?></li> | |
<?php endforeach; ?> | |
</ul> | |
<?php endforeach; ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment