I am trying to order my terms numeric. But the problem is that nog every term is numeric. So I have the following terms (check image below) which some of them are dimensions and some are others. As you can see, my get_terms() function, orders them by name, but if they are numeric it only looks at the first character. So 1400mm is less than 500mm.

I don't know where I need to begin. Should I try to modify the result of get_terms() or hook into the get_terms_orderby() function. But I have no idea how to do this.

My code to show the terms:

$taxonomy = 'product-filter';
$parents = get_terms( $taxonomy, array( 'hide_empty' => false, 'parent' => 0, 'orderby' => 'id' ) );
if( ! empty( $parents ) ) {
    foreach( $parents as $parent ) {
        echo '<ul>';
        echo '<h2>' . $parent->name . '</h2>';
        $children = get_terms( $taxonomy, array( 'hide_empty' => false, 'child_of' => $parent->term_id ) );
        foreach( $children as $child ) {
            echo '<li><label><input type="checkbox">' . $child->name . ' (' . $child->count . ')</label></li>'; 
        echo '</ul>';

enter image description here


You can use usort to sort the object $children.

The function to sort after you got the $children object can be like this:

usort( $children, function($a, $b) {
    $ai = filter_var($a->name, FILTER_SANITIZE_NUMBER_INT);
    $bi = filter_var($b->name, FILTER_SANITIZE_NUMBER_INT);
    if ($ai == $bi) {
        return 0;
    return ($ai < $bi) ? -1 : 1;
  • Thanks, this works. Can you explain your code? – Robbert Nov 11 '15 at 13:45
  • You can check php.net/manual/en/function.usort.php for more detail on usort. filter_var($b->name, FILTER_SANITIZE_NUMBER_INT) to get number from your term name. – Tung Du Nov 11 '15 at 13:47
  • The aim of using usort is sorting your $children object by the object field. In here, we sorting by the name of term, but we want to sort by that value (numeric value), so we must extract the number from the name by using function I comment above. – Tung Du Nov 11 '15 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.