首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在帖子中显示标签,顺序计数(大多数使用)不按字母顺序排列?

如何在帖子中显示标签,顺序计数(大多数使用)不按字母顺序排列?
EN

WordPress Development用户
提问于 2018-04-13 05:04:49
回答 1查看 582关注 0票数 2

我想首先显示最常用的标签在单一的帖子页,档案页和主页。

For示例:

我有4个标签--Ball(5个帖子)、Doll(3个帖子)、(2个帖子)、Apple(1个帖子)。每当我在一个帖子中放置多个标签时,这些标签按字母顺序显示,但我想先显示最常用的标签。

EN

回答 1

WordPress Development用户

发布于 2018-04-13 06:36:05

这是可能的,首先使用get_the_tags()获取原始标记数据,然后用usort()对每个标记的count属性排序结果,然后循环它们并将它们作为链接输出:

代码语言:javascript
复制
/*
 * Get array of tags and sort by count.
 */
$tags = get_the_tags();

if ( $tags && ! is_wp_error( $tags ) ) {
    usort( $tags, function( $a, $b ) {
        return $b->count - $a->count; // Swap $a and $b for ascending order.
    } );

    /*
     * Get an HTML link for each tag and put in an array.
     */
    $links = array();

    foreach ( $tags as $tag ) {
        $links[] = '' . $tag->name . '';
    }

    /*
     * Output links separated by comma.
     */
    echo implode( ', ', $links );
}

另一个实现是创建一个the_tags()包装器,它通过wp_list_sort()过滤器重新排序标记:

代码语言:javascript
复制
/**
 * Retrieve the tags for a post, ordered by post count.
 *
 * @param string $before Optional. Before list.
 * @param string $sep    Optional. Separate items using this. 
 * @param string $after  Optional. After list.
 */
function the_tags_wpse( $before = null, $sep = ', ', $after = '' ) {
    add_filter( 'get_the_terms', $callback = function( $tags ) {
        return wp_list_sort( $tags, 'count', 'desc' );
    }, 999 );
    the_tags( $before, $sep, $after );
    remove_filter( 'get_the_terms', $callback, 999 );  
}
票数 3
EN
页面原文内容由WordPress Development提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://wordpress.stackexchange.com/questions/300658

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档