Skip to content

Instantly share code, notes, and snippets.

@krasenslavov
Last active February 26, 2019 09:02
Show Gist options
  • Save krasenslavov/5b3b91dcb16ee604b0000aed566b66ba to your computer and use it in GitHub Desktop.
Save krasenslavov/5b3b91dcb16ee604b0000aed566b66ba to your computer and use it in GitHub Desktop.
WooCommerce product categories hierarchy (in array).
<?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