订购Foreach循环结果 [英] Order Foreach loop results

查看:45
本文介绍了订购Foreach循环结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I cannot use the 'orderby' => 'post_count' as contributors have multiple posts assigned to them.

相反,对于每个用户输出,我使用count_user_posts()函数获得其$ post_count.

Rather, for each user output, I get their $post_count using the count_user_posts() function.

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

How can I re-order the items based on this number? Highest to lowest?

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

The user post count is not part of the $users array :(

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

推荐答案

您可以将 usort 与自定义功能一起使用:

You can use usort with a custom function:

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 参考)

And you can also use _post_count in the other foreach, since the sorting modified each element ( $a and $b are passed by reference )

这篇关于订购Foreach循环结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆