Last active
February 26, 2019 09:02
-
-
Save krasenslavov/5b3b91dcb16ee604b0000aed566b66ba to your computer and use it in GitHub Desktop.
WooCommerce product categories hierarchy (in array).
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 | |
function get_woocats_arr( $parent = 0, $hierarchy = array() ) { | |
$categories = get_terms( | |
array( | |
'taxonomy' => 'product_cat', | |
'orderby' => 'count', | |
'child_of' => $parent, | |
) | |
); | |
foreach ( $categories as $category ) { | |
if ( 0 === $category->parent ) { | |
$hierarchy[ $category->term_id ] = array( | |
'slug' => $category->slug, | |
'name' => $category->name, | |
'children' => array(), | |
); | |
get_woocats_arr( $category->term_id, $hierarchy ); | |
} else { | |
$hierarchy[ $category->parent ]['children'][] = array( | |
'slug' => $category->slug, | |
'name' => $category->name, | |
'children' => array(), | |
); | |
} | |
} | |
return $hierarchy; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment