Last active
March 24, 2021 14:49
-
-
Save AcademicHumber/3355c5daeb791f9eeb5f087093d6f865 to your computer and use it in GitHub Desktop.
Wordpress: Function to make an array of elements from an specific taxonomy even at a second level of hierarchy
This file contains 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 rc_get_categories_data() | |
{ | |
$categories_data = []; | |
$taxonomy = 'category'; //change this with the taxonomy you want | |
$orderby = 'name'; | |
$show_count = 0; | |
$pad_counts = 0; | |
$hierarchical = 1; | |
$title = ''; | |
$empty = 0; | |
$args = array( | |
'taxonomy' => $taxonomy, | |
'orderby' => $orderby, | |
'show_count' => $show_count, | |
'pad_counts' => $pad_counts, | |
'hierarchical' => $hierarchical, | |
'title_li' => $title, | |
'hide_empty' => $empty | |
); | |
$all_categories = get_categories($args); | |
foreach ($all_categories as $category) { | |
if ($category->category_parent == 0) { | |
$category_id = $category->term_id; | |
$args2 = array( | |
'taxonomy' => $taxonomy, | |
'child_of' => 0, | |
'parent' => $category_id, | |
'orderby' => $orderby, | |
'show_count' => $show_count, | |
'pad_counts' => $pad_counts, | |
'hierarchical' => $hierarchical, | |
'title_li' => $title, | |
'hide_empty' => $empty | |
); | |
$sub_cats = get_categories($args2); | |
$categories_data[$category->name] = ['name' => $category->name, 'slug' => $category->slug, 'sub-categories' => []]; | |
if ($sub_cats) { | |
foreach ($sub_cats as $sub_category) { | |
$categories_data[$category->name]['sub-categories'][$sub_category->name] = ['name' => $sub_category->name, "slug" => $sub_category->slug]; | |
} | |
} | |
} | |
} | |
return $categories_data; | |
} | |
$categories_data = rc_get_categories_data(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The output: