I have the following code which works exactly as i'd like it to, but the displayed tags are in reverse alphabetical order and i'm not sure how to sort. I've noticed that the_tags has an argument called "order" that allows ordering, but get_the_tags does not. Is this because i stored the tags (when adding them with wordpress admin area) in the order that they are being displayed in? CAn i not sort them when calling the array? I'd hate to have to delete the 3 tags and re-add them in order, as this is not very flexible should i want to add another tag in the future that begins with "A", for example. Does that makes sense? :D

$post_tags = get_the_tags();
if (is_array($post_tags) || is_object($post_tags)) {
foreach( $post_tags as $tag) :
    if ( $tag->name === 'Nut Free' ) :

<span title="Nut Free!" class="post-inline-tag nut-free">NF</span>

    elseif ( $tag->name === 'Gluten Free' ) :

<span title="Gluten Free!" class="post-inline-tag gluten-free">GF</span>

    elseif ( $tag->name === 'Soya Free' ) :

<span title="Soya Free!" class="post-inline-tag soya-free">SF</span>

    else :
    // Post has neither tag, do nothing.

Resulting image: I'd like the result to be "GF, NF, SF".


There are always workarounds to implement the sorting:

Add this function:

function se_sort_tags_alphabetically( $tags = array() ) {
    if ( $tags ) {
        $sortData = $sorted = array();
        foreach ( $tags as $i => $tag ) {
            if ( empty( $tag->name ) ) continue;
            $sortData[$tag->name] = $i;
        foreach ( $sortData as $index ) {
            $sorted[$index] = $tags[$index];
        $tags = $sorted;
    return $tags;

Then use:

$post_tags = se_sort_tags_alphabetically(get_the_tags());

Hope that helps.

  • I copied the function to functions.php and substituted $post_tags = get_the_tags(); for the line you gave me but this isn't working. They are still displaying, but they are not sorted. Any ideas? Also, thank you for taking the time to write that for me :)
    – brad
    Nov 15 '16 at 21:51
  • Just to clarify, i now have this (i cleaned up with echos a little): prntscr.com/d7rd2t
    – brad
    Nov 15 '16 at 22:04
  • 1
    Using krsort instead of ksort fixed my issue. Thank you Samuel!! :)
    – brad
    Nov 18 '16 at 7:42
  • You're welcome. Please edit my answer to add krsort as it helped.
    – Ismail
    Nov 18 '16 at 8:59

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.