【问题标题】:Custom taxonomies won't display alphabetically自定义分类不会按字母顺序显示
【发布时间】:2015-12-14 14:23:40
【问题描述】:

有没有人知道为什么会这样。 Wordpress 按插入的顺序而不是字母顺序列出了我的自定义分类法。这是我正在使用的代码。

function get_the_term_list_inclusief( $id, $taxonomy, $before = '', $sep = '', $after = '') {
$terms = get_the_terms( $id, $taxonomy );

if ( is_wp_error( $terms ) )
    return $terms;


if ( empty( $terms ) )
    return false;

$links = array();

foreach ( $terms as $term ) {
    $link = get_term_link( $term, $taxonomy );
    if ( is_wp_error( $link ) ) {
        return $link;
    }
    $links[] = '<a class="ajax" href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>';
}

/**
 * Filter the term links for a given taxonomy.
 *
 * The dynamic portion of the filter name, `$taxonomy`, refers
 * to the taxonomy slug.
 *
 * @since 2.5.0
 *
 * @param array $links An array of term links.
 */
$term_links = apply_filters( "term_links-$taxonomy", $links );

return $before . join( $sep, $term_links ) . $after;

}

是否可以使用此代码并按标题或 ASC 对分类进行排序?

谢谢

【问题讨论】:

  • 一个简单的 sort($terms) 在你的 foreach 循环之前可能......?
  • 像这样:$links = array(); sort($terms); foreach ( $terms as $term ) { ?
  • @CBroe,那没用。我把它放在函数上,但没有运气。
  • 我明白了,get_the_terms 不只是返回分类术语名称,而是一个对象数组。所以它可能更需要 usort 和一个小的自定义比较函数,根据它们的 name 属性比较两个对象。
  • 是的,这简直让我大吃一惊……

标签: wordpress


【解决方案1】:

试试这是否可行:

// ...
$links = array();

usort($terms, function($a, $b) {
  return strcmp($a->name, $b->name);
});

foreach ( $terms as $term ) {
// ...

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 2015-08-14
    • 2014-10-13
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2019-12-16
    相关资源
    最近更新 更多