开发者

Get Authors Randomly

开发者 https://www.devze.com 2023-02-21 19:01 出处:网络
how to get authors details and author page permalink randomly. I have checked the new get_users() function for wordpress which is returning the author but i can not sorting them randomly.

how to get authors details and author page permalink randomly. I have checked the new get_users() function for wordpress which is returning the author but i can not sorting them randomly.

here is the site i am using the code: http://citystir.com

Any help?


Solution: Thanks to theomega i have solved the isse. Here is the code just for community sharing:

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

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

Did not set the limit on the $args because i need the shuffle in all users. Hope it w开发者_如何学编程ill help someone out there, in the wild. :D Thanks!


Try

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

Using the PHP Shuffle-Function.


We can use the get_users() to get a list of authors, users with a specific role, user with specific meta, etc. The function returns users which can be ordered by ID, login, nicename, email, url, registered, display_name, post_count, or meta_value. But there is no random option such as what get_posts() function provides to shows posts randomly.

Since the get_users() function uses WP_User_Query class, there is an action hook pre_user_query we can use to modify the class variable. The idea is using our own ‘rand’ order by parameter. If we put “rand” to the orderby parameter, “user_login” will be used instead. In this case, we need to replace it with RAND() to result users randomly. In this example below, we I ‘rand’ and you can use your own order by name.

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;
}

The WP_User_Query contains order by query and the our arguments. Now, we have a new order by parameter to WordPress.

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消