Opened 13 months ago

Last modified 12 months ago

#20606 new feature request

orderby rand param does not work with either WP_User_Query or get_users

Reported by: kjmeath Owned by:
Priority: normal Milestone: Awaiting Review
Component: Users Version: 3.2.1
Severity: normal Keywords:
Cc: kovshenin@…, kpayne@…

Description

Using WordPress 3.2.1

$contributors = get_users(array('role' => 'contributor', 'orderby' => 'rand', 'number' => 3));
$wp_user_search = new WP_User_Query(array('role' => 'contributor', 'orderby' => 'rand', 'number' => 3));
$contributors = $wp_user_search->get_results();	

Change History (2)

  • Cc kovshenin@… added
  • Cc kpayne@… added

The WP_User_Query::prepare_query() method limits the fields you can order by. You can, however, edit the SQL ORDER BY clause directly by hooking pre_user_query action.

<?php

// Create a function to override the ORDER BY clause
$randomize_func = create_function( '&$query', '$query->query_orderby = "ORDER BY RAND()";' );

// Hook pre_user_query
add_action( 'pre_user_query', $randomize_func );

// Make the call
$contributors = get_users( array( 'role' => 'subscriber', 'orderby' => 'rand', 'number' => 3 ) );

// Remove the hook
remove_action( 'pre_user_query', $randomize_func );
Note: See TracTickets for help on using tickets.