Trying to Add PHP Variables Results in Last Value Being Dropped

This is within a WordPress site. I’ve got custom field data that’s being stored as a number. The specific values are currently 33, 24, 14 and 21. I’m trying to add them together so I can display the total count elsewhere. Here’s my PHP function:

    function total_video_course_time($course_ID) {

      if (empty($course_ID)) {
          $course_ID = get_the_ID();
      }
      $args = array(
        'post_type' => 'lesson',
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key'     => '_lesson_course',
                'value'   => $course_ID,
                'compare' => '=',
            ),
            array(
                'key' => '_lesson_length',
                'value'   => '',
                'type'    => 'numeric',
                'compare' => '!=',
            ),
        ),
      );
      $lessoncount = 0;
      $customfieldvalue = 0;
      $the_query = new WP_Query( $args ); 
      if ( $the_query->have_posts() ) {
        while ( $the_query->have_posts() ) : $lessoncount = $lessoncount + $customfieldvalue; $the_query->the_post(); 
            $customfieldvalue = get_post_meta( get_the_ID(), '_lesson_length', true );
            echo get_the_title().': '.$customfieldvalue.'<br>';

        endwhile;
      } 
      wp_reset_postdata();
      return $lessoncount;
}

So in the loop there, $customfieldvalue = get_post_meta( get_the_ID(), '_lesson_length', true ); is getting those values I mentioned. And since right now I have echo get_the_title().': '.$customfieldvalue.'<br>'; I can verify that all four values are being retrieved.

Read More

However, $lessoncount = $lessoncount + $customfieldvalue; is supposed to be counting them all, but I only end up with 71 (the total of the first three numbers), not 92.

Any idea what I’m doing wrong?

Related posts

1 comment

  1. You’re adding $customfieldvalue before retrieving it the first time:

    // ...                $customfieldvalue hasn't been retrieved here        vvv
    while ( $the_query->have_posts() ) : $lessoncount = $lessoncount + $customfieldvalue; $the_query->the_post(); 
        $customfieldvalue = get_post_meta( get_the_ID(), '_lesson_length', true );
    // ...
    

    You should move the equation to the end of the while loop:

    while ( $the_query->have_posts() ) : $the_query->the_post(); 
        $customfieldvalue = get_post_meta( get_the_ID(), '_lesson_length', true );
        echo get_the_title().': '.$customfieldvalue.'<br>';
    
        $lessoncount += $customfieldvalue;
    endwhile;
    

Comments are closed.