在 Wordpress 中显示随机分类术语 [英] Displaying random Taxonomy terms in Wordpress

查看:24
本文介绍了在 Wordpress 中显示随机分类术语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 wordpress 中根据标题按字母顺序显示随机分类术语.

I am trying to display random taxonomy terms in wordpress ordered alphabetically according to its title.

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

I am using the following code which does display the categories randomly but is not displayed alphabetically.

<?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 默认按名称排序

Since get_terms orders by name by default

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> ';
  }
}

这篇关于在 Wordpress 中显示随机分类术语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆