0

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

    <?php
$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>

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

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

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

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

<?php
    else :
    // Post has neither tag, do nothing.
    endif; 
endforeach;
}
?>

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

1 Answer 1

2

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;
        }
        krsort($sortData);
        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.

4
  • 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
    Commented Nov 15, 2016 at 21:51
  • Just to clarify, i now have this (i cleaned up with echos a little): prntscr.com/d7rd2t
    – brad
    Commented Nov 15, 2016 at 22:04
  • 1
    Using krsort instead of ksort fixed my issue. Thank you Samuel!! :)
    – brad
    Commented Nov 18, 2016 at 7:42
  • You're welcome. Please edit my answer to add krsort as it helped.
    – Ismail
    Commented Nov 18, 2016 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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