Support

Account

Home Forums Front-end Issues Find Sum of Custom Field Values from Different Posts Reply To: Find Sum of Custom Field Values from Different Posts

  • If I understand what you’re looking for then something like this should do it.

    
    <?php 
      
      // not sure if you need this
      // if a template file then probably not
      global $post;
      
      // multidimensional array to hold stats
      $stats = array();
      
      $args = array(
        'post_type' => 'seasons', // not completely sure of post type
        'posts_per_page' => -1
      );
      $season_query = new WP_Query($args);
      if ($season_query->have_posts()) {
        if (have_rows('stats_bloc_m')) {
          while(have_rows('stats_blog_m')) {
            the_row();
            $competition = get_sub_field('competition_m');
            if (!isset($stats[$competition])) {
              $stats[$competition] = 0;
            }
            if (have_rows('competition_stats_m')) {
              while (have_rows('competition_stats_m')) {
                the_row();
                $stats[$competition] += get_sub_field('goals_m');
              } // end while have_rows('competition_stats_m')
            } // end if have_rows('competition_stats_m')
          } // end while have_rows('stats_blog_m')
        } // end if have_rows('stats_bloc_m')
      
      } // end if have posts
      
      if (count($stats)) {
        foreach ($stats as $competitions => $goals) {
          ?>
            <p><?php echo $competition; ?><br />Goals: <?php echo $goals; ?></p>
          <?php 
        } // end foreach stats
      } // end if count stats
      
    ?>