首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Wordpress中显示随机分类法术语

问在Wordpress中显示随机分类法术语
EN

Stack Overflow用户
提问于 2015-06-12 07:34:13
回答 1查看 3.2K关注 0票数 2

我试图在wordpress中显示随机的分类法术语,按标题按字母顺序排列。

我正在使用下面的代码,它会随机显示类别,但不会按字母顺序显示。

代码语言:javascript
复制
<?php
//display random sorted list of terms in a given taxonomy
$counter = 0;
$max = 5; //number of categories to display
$taxonomy = 'cp_recipe_category';
$terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0');
shuffle ($terms);
//echo 'shuffled';
if ($terms) {
foreach($terms as $term) {
    $counter++;
    if ($counter <= $max) {
    echo '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
    }
}
}
?>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-06-12 07:37:16

因为默认情况下get_terms按名称订购

代码语言:javascript
复制
get_terms('taxonomy='.$taxonomy.'&hide_empty=0');

应该就够了。

按字母顺序得到随机项

代码语言:javascript
复制
<?php

$max = 5; //number of categories to display
$taxonomy = 'cp_recipe_category';
$terms = get_terms('taxonomy='.$taxonomy.'&orderby=name&order=ASC&hide_empty=0');

// Random order
shuffle($terms);

// Get first $max items
$terms = array_slice($terms, 0, $max);

// Sort by name
usort($terms, function($a, $b){
  return strcasecmp($a->name, $b->name);
});

// Echo random terms sorted alphabetically
if ($terms) {
  foreach($terms as $term) {
    echo '<p><a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term->name.'</a></p> ';
  }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30797697

复制
相关文章

相似问题

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