Home » Wordpress » get_tags() function not sorting properly

get_tags() function not sorting properly

Posted by: admin November 30, 2017 Leave a comment

Questions:

Despite lots of documentation and examples online, I’m can’t seem to make this simple function work properly. I have no idea what I’m doing wrong, but nonetheless, this isn’t working properly. Can anyone spot what I’m missing here?

I’m looking to make a custom Tag Cloud, which is why I’m not using wp_tag_cloud().

$tags = get_tags( array('orderby' => 'name', 'order' => 'ASC'));
    foreach($tags as $tag) {
        echo "<li><a href=\""
                    .get_tag_link($tag->term_id)."\">"
                    .ucwords($tag->name)
                    ."</a> ($tag->count related page)</li>";    
    }

This produces the following output:

 - Black Box (3 related page)
 - Waste (2 related page)
 - Recycling (2 related page) 
 - Garbage (1 related page) 
 - Cheese (1 related page)
 - Blue Box (1 related page) 
 - Test (1 related page)

As you can see, they’re sorted by COUNT, and not name. I have no idea why. My arguments seem to be ok. thoughts?

Answers:

This question is old, but maybe this help someone still searching for answer.

function sortOrder($a, $b) {
    if($a->name == $b->name){ return 0 ; }
    return ($a->name < $b->name) ? -1 : 1;
}

$tags = get_tags();
usort($tags, 'sortOrder');

    foreach($tags as $tag) {
        echo "<li><a href=\""
                    .get_tag_link($tag->term_id)."\">"
                    .ucwords($tag->name)
                    ."</a> ($tag->count related page)</li>";    
    }

Questions:
Answers:

I found this question while trying to fix a similar issue… turns out my code just had a small typo (‘orderby ‘ instead of ‘orderby’). But I found something that might help you.

It seems as if this is sometimes caused by plugins interfering with your query. Try disabling your plugins to see if this fixes the issue.