Skip to content

Instantly share code, notes, and snippets.

@SteveJonesDev
Last active February 7, 2017 03:27
Show Gist options
  • Save SteveJonesDev/34e72ebac1984ef14f9b0328fd544a1e to your computer and use it in GitHub Desktop.
Save SteveJonesDev/34e72ebac1984ef14f9b0328fd544a1e to your computer and use it in GitHub Desktop.
Wordpress WP_User_Query - Query by meta with random ordering
<?php
/*
WP_User_Query orderby random
put this in functions.php
*/
add_filter('pre_user_query', function(&$query) {
if($query->query_vars["orderby"] == 'rand') {
$query->query_orderby = 'ORDER by RAND()';
}
});
?>
<?php
// WP_User_Query Arguments
$args = array(
'has_published_posts' => array('post'),
'fields' => array( 'ID','display_name','user_nicename' ),
'orderby' => 'rand',
'number' => 6,
'meta_key' => 'featured_truthteller',
'meta_value' => 'yes',
'meta_compare' => 'NOT LIKE',
);
// WP_User_Query
$user_query = new WP_User_Query( $args );
$users = $user_query->get_results();
print_r($users);
// Loop Users
if( $users ) {
foreach( $users as $user ) {
if ( count_user_posts( $user->id ) >= 1 ) {
echo $user->display_name;
echo get_avatar($user->ID, 300);
echo get_bloginfo('url')."/author/".$user->user_nicename;
}
}
} else {
echo "no users found";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment