How to Orderby User Role?

时间:2012-07-03 作者:Mike

我正在按用户角色订购帖子。。。我目前有2个用户角色(打算创建更多),它们是“高级用户”和“用户”,以及一些由“管理员”创建的POS

所有这些帖子都在一个页面上,我希望所有由“高级用户”撰写的帖子都在顶部,然后是下面的其他帖子。

我目前已经用两个单独的循环完成了这项工作,然而,随着网站的发展,将需要添加分页,而使用两个单独的循环,这将不起作用。

感谢您的帮助!

谢谢

1 个回复
SO网友:kaiser

这有点困难,因为没有默认的用户角色元键或post数据。我们唯一得到的是用户ID。

// Get the posts
$posts_by_author_ID = get_posts( array(
     \'post_type\'   => \'post\'
    ,\'post_status\' => \'publish\'
    ,\'orderby\'     => \'post_author\'
    ,\'order\'       => \'DESC\'
) );
foreach ( $posts_by_author_ID as $post )
{
    static $user;

    $new_user = get_user_by( \'id\', $post->post_author );

    // Let\'s save some queries
    if ( 
        isset ( $user ) 
        AND $user->ID === $new_user->ID
    )
        continue;

    $user = $new_user;

    foreach ( $user->roles as $role )
    {
        $posts_by_author_role[ $role ] = array( 
             \'user\' => $user
            ,\'post\' => $post
        );
    }
}
// Sort by key a.k.a. role
ksort( $posts_by_author_ID );

echo \'<pre>\'; // Only for debugging/developing - should get deleted when done
foreach ( $posts_by_author_ID as $role => $data )
{
    list( $user, $post ) = $data;
    // Now we can output our data
    // The user data is saved inside $user
    // The actual post data is saved inside $data

    // The following is only for debugging/developing - should get deleted when done
    var_export( $user, false );
    var_export( $post, false );
}
echo \'</pre>\'; // Only for debugging/developing - should get deleted when done

结束

相关推荐