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).

    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'); ?>

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

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

Thank you!

  • are you sure the team names wouldn't be better as a taxonomy? Querying for posts by their post meta values carries a very big performance cost, and setting posts_per_page to -1 is also considered bad practice for performance/memory reasons. Likewise the requirement to do math in your query makes it even heavier. Can you not pre-calculate totals? E.g. updating the total for a team when they win a game? I ask because the path you've chosen is the most expensive/slowest/heaviest path, assuming it's possible – Tom J Nowell Dec 5 '20 at 0:51
  • Otherwise you'll have to add up the points in PHP – Tom J Nowell Dec 5 '20 at 0:52
  • @TomJNowell something I didn't even think about. (Taxonomy). Basically I should attach each of these posts to a Taxonomy Term (Team Names), and then query by Taxonomy? – Joe Dec 5 '20 at 1:00
  • @TomJNowell to add, these CPT entries are actually being created by NinjaForms submissions. I'll have to see if I can automatically assign Taxonomy based select value upon form submit. – Joe Dec 5 '20 at 1:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.