【问题标题】:Order Foreach loop results订购 Foreach 循环结果
【发布时间】:2015-05-30 16:35:45
【问题描述】:

我不能使用 'orderby' => 'post_count' 因为贡献者有多个帖子分配给他们。

相反,对于每个用户输出,我使用 count_user_posts() 函数获取他们的 $post_count。

如何根据此编号重新订购商品?从高到低?

用户发帖数不是 $users 数组的一部分 :(

            // order contributors
            $args = array(
                'role' => contributors,
                'orderby' => 'post_count',
                'order' => 'ASC',
                'fields' => 'all'
            );

            // The Query
            $user_query = new WP_User_Query( $args );
            $users = $user_query->get_results();

            echo '<ul>';
            $i = 0;
            foreach ( $users as $user ) {

                $post_count = count_user_posts( $user->id );

                if ( count_user_posts( $user->id ) >= 1 ) {
                    echo '<li class="ws-sort" data-sort="' . $post_count . '"><a href="' . site_url() . '/author/' . $user->user_nicename . '">' . $user->display_name . '</li>';
                    if (++$i == 8) break;
                }
            }
            echo '</ul>';

【问题讨论】:

  • 需要对$users数组进行排序吗?
  • 我不能这样做,因为 $post_count 是为循环中的每个人设置的。我不能把它拿到外面。

标签: php wordpress foreach


【解决方案1】:

您可以将usort 与自定义函数一起使用:

usort($users, function(&$a,&$b) {
    if (!isset($a->_post_count)) $a->_post_count = count_user_posts( $a->id );
    if (!isset($b->_post_count)) $b->_post_count = count_user_posts( $b->id );
    return  $a->_post_count < $b->_post_count;
});

你也可以在另一个foreach中使用_post_count,因为排序修改了每个元素($a和$b通过引用传递)

【讨论】:

  • 这看起来很有趣,我对上面在我的 for 循环上下文中的位置有点困惑?
  • 刚刚完成$users = $user_query-&gt;get_results();
  • 梅林的胡子!看起来有,请原谅双关语对问题的分类。谢谢和赞赏。
  • 很高兴您回答了我的问题。我还想问一下,因为我们现在已经按 post_count 过滤了,是否可以通过另一个排序条件对该结果进行排序?所以 post_count,然后按字母顺序?或者你只能有一个排序顺序?谢谢。
  • 使用自定义函数,排序条件可以是任何你想要的,在这种情况下我使用$a-&gt;_post_count &lt; $b-&gt;_post_count,但可以是,例如$a-&gt;_post_count &lt; $b-&gt;_post_coun &amp;&amp; $a-&gt;username。只需找到正确的表达式即可返回您需要的订单
猜你喜欢
  • 1970-01-01
  • 2014-12-05
  • 1970-01-01
  • 2017-03-10
  • 2015-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多