如何在每个页面刷新时以随机顺序显示wordpress分类法类别

时间:2016-04-04 13:20:24

标签: wordpress taxonomy

我需要在每次页面刷新时以随机顺序显示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个类别被提取,其余的被忽略。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我建议尝试一下:

  1. taxonomy
  2. 中检索所有字词
  3. 使用php函数随机返回数组的随机播放 shuffle()
  4. 通过foreach loop
  5. 传递
  6. 创建一个新数组,然后使用array_slice获取前4个数组 条目(在您的示例中如您所愿)。
  7. 喜欢这个粗略的想法:

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

    我希望它适合你,谢谢!