4

I'm displaying a list of terms that a post is assigned to by using the following:

<?php 
$terms = get_the_terms( $post->ID , 'winetype' ); 
$sep = ', '; 
foreach ( $terms as $term ) { 
echo $term->name; 
echo $sep; 
} ?>

But we would like the output to be in descending alphabetical order (Z-A), I can't find a way to use order => DESC on this, any suggestions?

Many thanks in advanced.

6

You could try this:

// Get posts terms
$terms = wp_get_post_terms( $post->ID, 'winetype', array( 'order' => 'DESC') );

$sep = ', '; 
foreach ( $terms as $term ) { 
    echo $term->name; 
    echo $sep; 
} 
  • 2
    Just note, this adds extra db calls for each and every post queried. Sorting the results from get_the_terms() with usort() might be a better idea – Pieter Goosen Apr 18 '16 at 16:59
2

Use wp_get_post_terms() instead:

<?php
$names = wp_get_post_terms(
    $post->ID,
    'winetype',
    array(
        'orderby' => 'name',
        'order' => 'DESC',
        'fields' => 'names'
    );

echo implode(', ', $names); // to avoid trailing separator

Updated by virtue of to @Pieter Goosen comment.

$terms = get_the_terms( $post->ID , 'winetype' ); 

if($terms) { // check the variable is not empty

    // compare terms
    function cmp($a, $b)
    {
        return strcmp($b->name, $a->name); // in reverse order to get DESC
    }

    // sort terms using comparison function
    usort($terms, 'cmp');

    // get names from objects
    function my_function($z)
    {
        return $z->name;
    }

    // map names array using my_function()
    $term_names = array_map('my_function', $terms);

    // define separator
    $separator = ', ';

    // get string by imploding the array using the separator 
    $term_names = implode($separator, $term_names);

    echo $term_names; // OR return

}
  • 1
    Just note, this adds extra db calls for each and every post queried. Sorting the results from get_the_terms() with usort() might be a better idea – Pieter Goosen Apr 18 '16 at 16:59
  • @PieterGoosen You are right. Thank you. I've updated the answer above. – Max Yudin Apr 19 '16 at 7:56

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.