Last active
June 26, 2024 14:53
-
-
Save mehrshaddarzi/8b927399f76b400dbf5e8efd819ba82d to your computer and use it in GitHub Desktop.
Get WordPress Terms Nested 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 | |
if (!class_exists('WP_Terms_Nested')) { | |
class WP_Terms_Nested | |
{ | |
public static function get($arg = []): array | |
{ | |
// @see https://developer.wordpress.org/reference/classes/wp_term_query/__construct/ | |
$defaults = [ | |
'taxonomy' => 'product_cat', | |
'order' => 'ASC', | |
'hide_empty' => true, | |
'fields' => 'all', | |
'parent' => 0 | |
]; | |
$args = wp_parse_args($arg, $defaults); | |
// Get Terms | |
$terms = get_terms($args); | |
// Sort children | |
$sorted_terms = []; | |
self::sort($terms, $sorted_terms); | |
// return data | |
return $sorted_terms; | |
} | |
public static function sort(array &$terms, array &$into, $parent_id = 0) | |
{ | |
foreach ($terms as $i => $term) { | |
if ($term->parent == $parent_id) { | |
$into[$term->term_id] = $term; | |
unset($terms[$i]); | |
} | |
} | |
foreach ($into as $top_term) { | |
$top_term->children = []; | |
self::sort($terms, $top_term->children, $top_term->term_id); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: