我想首先显示最常用的标签在单一的帖子页,档案页和主页。
For示例:
我有4个标签--Ball(5个帖子)、Doll(3个帖子)、猫(2个帖子)、Apple(1个帖子)。每当我在一个帖子中放置多个标签时,这些标签按字母顺序显示,但我想先显示最常用的标签。
发布于 2018-04-13 06:36:05
这是可能的,首先使用get_the_tags()获取原始标记数据,然后用usort()对每个标记的count属性排序结果,然后循环它们并将它们作为链接输出:
/*
* 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()过滤器重新排序标记:
/**
* 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 );
}https://wordpress.stackexchange.com/questions/300658
复制相似问题