我需要在每次页面刷新时以随机顺序显示wordpress分类法类别。我尝试了以下
function get_terms_dropdown($taxonomies, $args){
$myterms = get_terms($taxonomies, $args);
function shuffle_assoc($list) {
if (!is_array($list))
return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[$key] = $list[$key];
}
return $random;
}
$outputmain ="<ul class='services_cat'>";
$output = array_slice(shuffle_assoc($myterms), 0, 11);
foreach($output as $term){
$root_url = get_bloginfo('url');
$term_taxonomy=$term->taxonomy;
$term_slug=$term->slug;
$term_name =$term->name;
$term_desc = $term->description;
$termdesc = get_field('homepage_desciption', $term);
$link = $root_url.'/?'.$term_taxonomy.'='.$term_slug;
$outputmain .="<li><a class='servicecatname'>".$term_name."</a><div class='termdesc'>".$termdesc."</div></li>";
}
$outputmain .="</ul>";
return $outputmain;
}
$taxonomies = array('services-category');
$args = array('orderby' => 'rand', 'number' => '4','hide_empty'=>false);
echo get_terms_dropdown($taxonomies, $args);
我的代码以随机顺序显示,但只有前4个类别被提取,其余的被忽略。
提前致谢。
答案 0 :(得分:0)
我建议尝试一下:
taxonomy
。shuffle()
。foreach loop
。array_slice
获取前4个数组
条目(在您的示例中如您所愿)。喜欢这个粗略的想法:
$all = get_terms( 'category' ); // Retrieve all the terms.
shuffle( $all ); // Shuffle that returned array randomly.
$term_names = []; // Create a new array.
foreach ( $all as $cat ) // Pass that through a foreach loop.
$term_names[] = $cat->name; // Fill the new array.
$output = array_slice( $q, 0, 5 ); // get the first 4 entries.
foreach ( $output as $key=>$value ) // Show values !
echo '<p>' . $value . '</p>';
我希望它适合你,谢谢!