按字母降序获取术语

时间:2016-04-18 作者:Adrian

我正在显示一个职位分配给的术语列表,方法如下:

<?php 
$terms = get_the_terms( $post->ID , \'winetype\' ); 
$sep = \', \'; 
foreach ( $terms as $term ) { 
echo $term->name; 
echo $sep; 
} ?>
但我们希望输出按字母降序(Z-A),我找不到一种方法来使用order=>DESC,有什么建议吗?

非常感谢您的光临。

2 个回复
最合适的回答,由SO网友:Robbert 整理而成

您可以尝试以下操作:

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

$sep = \', \'; 
foreach ( $terms as $term ) { 
    echo $term->name; 
    echo $sep; 
} 

SO网友:Max Yudin

使用wp_get_post_terms() 而是:

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

echo implode(\', \', $names); // to avoid trailing separator
Updated 凭借to@Pieter Goosen评论。

$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

}

相关推荐

如何在WooCommerce_Account_Orders函数中传递$CURRENT_PAGE?

woocommerce功能woocommerce_account_orders($current_page) 已调用1个参数$current_page. 该函数通过调用woocommerce_account_orders_endpoint 通过以下挂钩-add_action( \'woocommerce_account_orders_endpoint\', \'woocommerce_account_orders\' );然而,在上述挂钩中,$current_page 未在函数中作为参数传递。情况如何$c