List users by sum of total custom fields for all their Posts
-
Ok, so I have a running site, and users can log their milage. Miles are a custom post type, with a custom field value as the actual number for the miles.
I want to list the users by who has the most miles, I know how to get all the miles for each user individually on their page, but I can’t figure out the foreach loop that I think I need… or if I need a custom database query.
Any help is greatly appreciated. Here is how I’m getting all of the sum of the custom field values for all their posts combined, I just need to do this for each user, and output them in a list format, with how many miles each has run total.
<?php //get current user global $current_user; get_currentuserinfo(); // build query of ids by user $userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'miles')); //change this // loop to create array of ids by user foreach ($userPosts as $post) { setup_postdata($post); $ids[] = get_the_ID(); } $idList = implode(",", $ids); //tun this crap into a list $meta_key = 'miles';//set this to your custom field meta key $allmiles = $wpdb->get_col($wpdb->prepare(" SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s AND post_id in (" . $idList . ")", $meta_key)); echo '<p>You\'ve completed ' . array_sum( $allmiles) . '</p>'; ?>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- The topic ‘List users by sum of total custom fields for all their Posts’ is closed to new replies.