Skip to content

Commit

Permalink
Merge pull request #155 from BeAPI/feature/terms-sort
Browse files Browse the repository at this point in the history
Sort terms by hierarchical order
  • Loading branch information
iazema authored Sep 20, 2023
2 parents a8307b3 + 09b0813 commit b9f0296
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
24 changes: 23 additions & 1 deletion classes/cli/_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,29 @@ public static function get_all_terms( $args = array(), $terms_args = array() ) {
return false;
}

return $results;
return self::hierarchical_sort_terms( $results );
}

/**
* Sort an array of WP_Terms by hierarchical order (parents first, then children, then grand-children...)
*
* @param WP_Term[] $terms
* @param int $parent
* @return WP_Term[]
* @author Ingrid Azéma
*/
private static function hierarchical_sort_terms( array $terms, int $parent = 0 ): array {
$sorted_terms = [];
foreach ( $terms as $term ) {
if ( $term->parent !== $parent || ! $term instanceof WP_Term ) {
continue;
}
$sorted_terms[] = $term;
$children = self::hierarchical_sort_terms( $terms, $term->term_id );
$sorted_terms = array_merge( $sorted_terms, $children );
}

return $sorted_terms;
}

/**
Expand Down
1 change: 0 additions & 1 deletion psalm.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
<?xml version="1.0"?>
<psalm
totallyTyped="false"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
Expand Down

0 comments on commit b9f0296

Please sign in to comment.