【问题标题】:WordPress. Get equal number of posts of each content typeWordPress。获得相同数量的每种内容类型的帖子
【发布时间】:2016-11-06 11:35:16
【问题描述】:

假设我要显示 30 个帖子:10 个“A”类型,10 个“B”类型和 10 个“C”类型。按发布日期排序。

我该怎么做?

我的意思是我可以做到

$args = array(
    'posts_per_page'   => 30,
    'post_type' => array("A", "B", "C"),
);

$posts = get_posts( $args );

但它只会给我带来 30 条最新帖子——而不是每条 10 条。

【问题讨论】:

    标签: php wordpress loops


    【解决方案1】:

    你可以创建一个函数并传入你想要的类型和数量,然后对它们运行一个 WP_Query,然后返回你的帖子。

    例如

    function so_getEqualPosts($number_posts, $post_types){
    
        $postsToReturn = array();
    
             foreach ($post_types as $post_type) {
    
                  $args = array(
                       'post_type' => $post_type,
                       'posts_per_page' => $number_posts,
                       'orderby' => 'date',
                       'order' => 'DESC'
                  );
    
                  $result = new WP_Query($args);
    
                  array_push($postToReturn, $result->posts);
              }
    
            usort($postsToReturn, function($a, $b) {
                return strtotime($a['post_date']) - strtotime($b['post_date']);
            });
    
        return $postsToReturn;
    }
    

    ** 以上更新以符合 OP 要求** 另一种方法是使用 StdClass;

    $postsToReturn = new StdClass();
    

    然后在每次迭代中添加到类中:

    $postsToReturn->$post_type = $result->posts;
    

    然后你可以调用它:

    $posts = so_getEqualPosts(30, ["A", "B", "C"]);
    

    然后应该可以通过以下方式访问帖子:

    $posts->A
    $posts->B
    $posts->C
    

    等等

    这是未经测试的,而且非常动态,但应该给你一个起点:)

    【讨论】:

    • 或者,如果您不想使用 StdClass,请将 $postsToReturn 设为数组,并在每次迭代时简单地 array_push($postsToReturn, $result->posts)。这将为您提供所有帖子的数组,而不是通过最终对象中的帖子类型访问。
    • 非常感谢您,但是是否可以将所有这些帖子按发布时间排序在一个数组中?
    • @Paradoxetion 是的,应该是。如果您使用替代方法 (array_push($postsToReturn, $result->posts)),您将获得所有帖子的数组。这里的困难是,每次迭代,虽然您可以使用 WP_Query ('orderby' => 'date', 'order' => 'DESC') 进行排序,但类型 A 将被排序和添加,然后类型 B 排序和添加,依此类推,但整个数组不会被排序 (尽管其中的每种类型都会被排序)。
    • 您需要对整个数组进行排序,您可以使用 usort 进行排序,例如....usort($array, function($a, $b) { return strtotime($a['post_date']) - strtotime($b['post_date']); }); 查看更新的答案。
    • 好的,明白了,但为什么我不能这样做 $a = get_posts($args1); $b = get_posts($args2); $c = get_posts($args3);然后只是合并+排序数组?还是您的方法在速度和优化方面更好?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-02
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多