![](/img/trans.png)
[英]Displaying terms of a multiple taxonomy linked to a post in wordpress
[英]Displaying random Taxonomy terms in Wordpress
我试图在 wordpress 中根据其标题按字母顺序显示随机分类术语。
我正在使用以下代码,它会随机显示类别,但不按字母顺序显示。
<?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> ';
}
}
}
?>
由于get_terms
默认按名称get_terms
get_terms('taxonomy='.$taxonomy.'&hide_empty=0');
应该够了。
按字母顺序获取随机术语
<?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> ';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.