Skip to content

Instantly share code, notes, and snippets.

@mehrshaddarzi
Last active June 26, 2024 14:53
Show Gist options
  • Save mehrshaddarzi/8b927399f76b400dbf5e8efd819ba82d to your computer and use it in GitHub Desktop.
Save mehrshaddarzi/8b927399f76b400dbf5e8efd819ba82d to your computer and use it in GitHub Desktop.
Get WordPress Terms Nested Array
<?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);
}
}
}
}
@mehrshaddarzi
Copy link
Author

mehrshaddarzi commented Jun 26, 2024

Example:

$terms = WP_Terms_Nested::get([
    'taxonomy' => 'product_cat',
    'parent' => 0,
    'orderby' => 'count'
]);
foreach ($terms as $term) {

    // Check is Nested
    if(isset($term->children) and !empty($term->children)) {
        
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment