【问题标题】:WordPress: Show random 4 categories with 3 last postsWordPress:随机显示 4 个类别和 3 个最后的帖子
【发布时间】:2018-04-24 11:18:21
【问题描述】:

我正忙着构建一行,该行将随机显示 4 个类别,其中包含类别标题及其下的 3 个最新帖子。但是我被困住了如何以随机顺序获取类别,因为“orderby”不起作用...

有人可以帮我吗?

我正在使用的代码:

 <?php
    //for each category, show all posts
    $cat_args   = array(
        'orderby' => 'rand',
        'order' => 'ASC'
    );
    $limit      = 4;
    $counter    = 0;
    $categories = get_categories($cat_args);

    foreach ($categories as $category):
        if ($counter < $limit) {
            $args  = array(
                'showposts' => 3,
                'category__in' => array(
                $category->term_id
            ),
            'caller_get_posts' => 1
        );
        $posts = get_posts($args);
        if ($posts) {
            echo '<h3><a href="' . get_category_link($category->term_id) . '" title="' . sprintf(__("View all posts in %s"), $category->name) . '" ' . '>' . $category->name . '</a> </h3>';
            foreach ($posts as $post) {
                setup_postdata($post);
?>

<p><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></p>

<?php
            } // foreach($posts
        } // if ($posts
    } // foreach($categories
?>

<?php
    $counter++;
    endforeach;
?>

【问题讨论】:

    标签: php wordpress random categories


    【解决方案1】:

    删除下面的代码。这仅适用于帖子。

    $cat_args   = array(
            'orderby' => 'rand',
            'order' => 'ASC'
        );
    

    使用如下代码:

    $categories = get_categories();
    shuffle ($categories); // Just add shuffle and you will get random categories.
    

    【讨论】:

      【解决方案2】:

      你可以用它来获取随机猫:

      $categories = get_the_category($my_query->post->ID);
      $catCount = count($categories);
      //select a random category id
      $id = rand(0,$catCount-1);
      //cat id
      $catId = $categories[$id]->term_id;
      
      and replace to lines like
      
      if(is_array($cat)) {
      $categories = get_the_category($my_query->post->ID);
      $catCount = count($categories);
      //select a random category id
      $id = rand(0,$catCount-1);
      //cat id
      $catId = $categories[$id]->term_id;
      } else {
      $catId = $cat;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-07-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-19
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多