【问题标题】:Trying to Add PHP Variables Results in Last Value Being Dropped尝试添加 PHP 变量会导致最后一个值被删除
【发布时间】:2015-09-10 22:24:52
【问题描述】:

这是在 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.'&lt;br&gt;';,所以我可以验证是否正在检索所有四个值。

然而,$lessoncount = $lessoncount + $customfieldvalue; 应该把它们都数一遍,但我最终只得到 71(前三个数字的总和),而不是 92。

知道我做错了什么吗?

【问题讨论】:

    标签: php wordpress counter


    【解决方案1】:

    您在第一次检索之前添加$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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      相关资源
      最近更新 更多