WP Query – grouping posts by same meta key, adding together values from another key

Question

I’m attempting to create a leaderboard for 8 teams that will play multiple games and earn different amount of points for each game.

The setup will be pulling entries from a custom post type game, which makes a post for time a game is played, having meta values for both team name: _team_name and points: _points.

There will be many entries and varying points, however many will share the same _team_name post meta.

I need to create a frontend list which groups these entries into matching team names who have made entries and merge / count up their points total into this same <li>

Something like this:

enter image description here

So far I’ve found some help to put this together (which does pull the team names), but I’m unsure how to go about the rest (merging in the points data for each group).

<?php
    function  query_group_by_filter($groupby){
       global $wpdb;
       return $wpdb->postmeta . '.meta_value ';
    }
?>
<?php add_filter('posts_groupby', 'query_group_by_filter'); ?>
<?php $leaderboard = new WP_Query(array(
    'post_type' => 'game',
    'post_status' => 'publish',
    'posts_per_page' => -1,
    'meta_key' => '_team_name'
)); 
?>

<?php remove_filter('posts_groupby', 'query_group_by_filter'); ?>

<ul>
    <?php while ( $leaderboard->have_posts() ) : $leaderboard->the_post(); ?>
    <li><?php echo reset(get_post_custom_values('_team_name')); ?>
    <?php endwhile; ?>
</ul>

Is this the best query practice for doing so, and could someone provide any insight on how to accomplish the points merging?

Thank you!

0
Joe 8 months 2020-12-04T18:10:40-05:00 0 Answers 11 views 0

Leave an answer

Browse
Browse