尝试添加 PHP 个变量导致最后一个值被删除

Trying to Add PHP Variables Results in Last Value Being Dropped

这是在 WordPress 站点内。我有存储为数字的自定义字段数据。具体值目前为 33、24、14 和 21。我正在尝试将它们相加,以便可以在别处显示总数。这是我的 PHP 函数:

    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;
}

所以在循环中,$customfieldvalue = get_post_meta( get_the_ID(), '_lesson_length', true ); 正在获取我提到的那些值。因为现在我有 echo get_the_title().': '.$customfieldvalue.'<br>';,所以我可以验证是否正在检索所有四个值。

不过,$lessoncount = $lessoncount + $customfieldvalue;本来应该是全部算出来的,结果我只算了71(前三个数字的总和),不是92。

知道我做错了什么吗?

您在第一次检索之前添加 $customfieldvalue

// ...                $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 );
// ...

您应该将等式移动到 while 循环的末尾:

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;