[wp-hackers] WP User Query sorting
Dobri
dyordan1 at ramapo.edu
Tue Aug 6 21:14:26 UTC 2013
I almost got it working (in a very ugly way). I've posted my function below and would appreciate an idea on how I can do this in a less in-wp's-guts way or at least how to include the users that don't have that meta (which currently disappear if you sort by the custom meta). Thanks for any help you guys can provide.
function user_custom_column_orderby( $query )
{
global $wpdb;
$vars = $query->query_vars;
if ( isset( $vars['orderby'] ) && ('my_meta1' == $vars['orderby'] || 'my_meta2' == $vars['orderby'] || 'my_meta3' == $vars['orderby'] ) ) {
$query->query_vars = $vars;
$query->query_fields = "SQL_CALC_FOUND_ROWS $wpdb->users.ID, GROUP_CONCAT( $wpdb->usermeta.meta_value ORDER BY $wpdb->usermeta.meta_key SEPARATOR ' ' ) AS {$vars['orderby']}";
$query->query_from = "FROM $wpdb->users LEFT JOIN $wpdb->usermeta ON $wpdb->users.ID = $wpdb->usermeta.user_id";
$query->query_where = "WHERE ($wpdb->usermeta.meta_key = '{$vars['orderby']}') GROUP BY $wpdb->users.ID";
$query->query_orderby = "ORDER BY {$vars['orderby']} {$vars['order']}";
}
return $query;
}
add_filter( 'pre_user_query', 'user_custom_column_orderby' );
This results in a query like
SELECT SQL_CALC_FOUND_ROWS wp_users.ID, GROUP_CONCAT( wp_usermeta.meta_value
ORDER BY wp_usermeta.meta_key
SEPARATOR ' ' ) AS my_meta1
FROM wp_users
LEFT JOIN wp_usermeta ON wp_users.ID = wp_usermeta.user_id
WHERE (
wp_usermeta.meta_key = 'my_meta1'
) ORDER BY my_meta1 ASC
~Dobri
On Tue, 6 Aug 2013, at 4:39 PM, Dobri wrote:
> Hey,
>
> why no love for the WP_User_Query ordering? I've noticed that you can specify meta key ordering for WP_Query but not for WP_User_Query. Would there be an easy way to do sorting on user meta then? Without doing a lot of SQL-level stuff? Posted below is what I currently have, which doesn't really work.. duh. Any help appreciated! Thanks!
>
> ========================================
>
> function user_custom_column_orderby( $query )
> {
> $vars = $query->query_vars;
> if ( isset( $vars['orderby'] ) && ('my_meta1' == $vars['orderby'] || 'my_meta2' == $vars['orderby'] || 'my_meta3' == $vars['orderby'] ) ) {
> $vars = array_merge( $vars, array(
> 'meta_key' => $vars['orderby'],
> 'orderby' => 'meta_value_num'
> ) );
> }
> $query->query_vars = $vars;
>
> return $query;
> }
> add_filter( 'pre_user_query', 'user_custom_column_orderby' );
>
> ========================================
>
> P.S. I also noticed this pesky guy in the WP_User_Query object:
> public 'query_orderby' => string 'ORDER BY user_login ASC' (length=23)
> Do I have to worry about it?
>
> ~Dobri
>
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
More information about the wp-hackers
mailing list