【问题标题】:Get Authors Randomly随机获取作者
【发布时间】:2011-03-31 15:48:47
【问题描述】:

如何随机获取作者详细信息和作者页面永久链接。我已经检查了 wordpress 的新 get_users() 函数,它返回了作者,但我不能随机排序它们。

这是我使用代码的网站:http://citystir.com

有什么帮助吗?


解决方案:感谢 theomega 我解决了这个问题。这是社区共享的代码:

$args = array('role' => 'author');

    $authors = get_users($args);
    shuffle($authors);
    $i = 0;
     foreach ($authors as $author): 
           if($i == 4) break;
           //do stuff
           $i++;
         endforeach;

没有设置 $args 的限制,因为我需要在所有用户中进行随机播放。希望它会帮助那里的人,在野外。 :D 谢谢!

【问题讨论】:

    标签: php wordpress wordpress-theming


    【解决方案1】:

    试试

    $users = get_users('ciriteria');
    shuffle($users)
    //users is now shuffled
    

    使用PHP Shuffle-Function

    【讨论】:

    • nop 返回 false 或空字符串。它可能不适用于查询结果。
    • 你说得对,我编辑了我的分析器,shuffle 在 php 中就位。
    • 不,不是,检查历史!
    • 哦!现在明白了:D.. 函数不返回任何值,只是随机播放。我花了一段时间才想起..谢谢!
    【解决方案2】:

    我们可以使用 get_users() 来获取作者列表、具有特定角色的用户、具有特定元的用户等。该函数返回的用户可以按 ID、登录、 nicename、email、url、registered、display_name、post_count 或 meta_value。但是没有随机选项,例如 get_posts() 函数提供的随机显示帖子。

    由于 get_users() 函数使用 WP_User_Query 类,我们可以使用一个动作挂钩 pre_user_query 来修改类变量。这个想法是通过参数使用我们自己的“rand”顺序。如果我们将 “rand” 放在 orderby 参数中,则将使用“user_login”。在这种情况下,我们需要将其替换为 RAND() 以随机生成用户。在下面的示例中,我们“rand”,您可以按名称使用您自己的订单。

    add_action( 'pre_user_query', 'my_random_user_query' );
    
    function my_random_user_query( $class ) {
        if( 'rand' == $class->query_vars['orderby'] )
            $class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );
    
        return $class;
    }
    

    WP_User_Query 包含查询顺序和我们的参数。现在,我们对 WordPress 有了新的按参数排序。

    $users = get_users( array(
        'orderby' => 'rand',
        'number'  => 5
    ));
    print_r( $users );
    

    参考:http://www.codecheese.com/2014/05/order-wordpress-users-random/

    【讨论】:

      猜你喜欢
      • 2014-06-16
      • 1970-01-01
      • 2011-06-04
      • 1970-01-01
      • 2019-06-11
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多