引导轮播不适用于foreach循环

时间:2018-07-12 05:46:58

标签: php wordpress bootstrap-4

  <div class="carousel-inner">
    <?php $output = '';
    $class = 'carousel-item';
    $query = new WP_Query( array( 'post_type' => 'testimonials' , 'posts_per_page' => -1,) ); 
    $posts = $query->posts; 
    foreach($posts as $post)  {    
      $active = ($k == 0) ? " active" : "";   
      $output .=
      $active = ($k == 0) ? " active" : "";   
      $output .=
      "<div class='{$class}{$active}'> 
        <p><?php echo the_content();?></p>
        <h4><?php echo the_title();?></h4>
      </div>"; } ?>
    <div class="carousel-item">
      <p><?php echo the_content();?></p>
      <h4><?php echo the_title();?></h4>
    </div>
  </div>

它不显示输出,我不知道我哪里错了,请为活动和不活动的类提供帮助

1 个答案:

答案 0 :(得分:1)

$ i使用不正确,您应该在循环开始之前使用它,而且$ k的定义不正确,您的结构也不正确。

请使用以下代码,让我知道它是否有效。

                    <div id="carouselExampleIndicators2" class="carousel slide" data-ride="carousel">
        <!--This loop is fetching correct data -->
        <ol class="carousel-indicators">
          <?php $the_query = new WP_Query( array( 'post_type' => 'testimonials' , 'posts_per_page' => -1,) ); 
            // The Loop
            if ( $the_query->have_posts() ) {
              $i = 0;
                while ( $the_query->have_posts() ) {
                    $the_query->the_post();
                if($i == 0) {
                  $activeClass = 'active';
                }
                else {
                  $activeClass = '';
                }
                    echo '<li data-id="'.$post->ID.'" data-target="#carouselExampleIndicators2" data-slide-to="'.$i.'" class="'.$activeClass.'">
                        <h2>'.get_the_title().'</h2>
                        <p>'.trim(strip_tags(get_the_content())).'</p>
                      </li>';
                $i++;
                }
                /* Restore original Post Data */
                wp_reset_postdata();
            }               
          ?>
        </ol>
      <div class="carousel-inner">
        <?php 
        $output = '';
        $class = 'carousel-item';
        $the_query = new WP_Query( array( 'post_type' => 'testimonials' , 'posts_per_page' => -1,) );             
        // The Loop
        if ( $the_query->have_posts() ) {
          $i = 0;
          while ( $the_query->have_posts() ) {
            $the_query->the_post();
            if($i == 0) {
              $activeClass = 'active';
            }
            else {
              $activeClass = '';
            }
            echo "<div class='{$class}{$activeClass}'> 
              <p>".get_the_content($post->ID)."</p>
              <h4>".get_the_title($post->ID)."</h4>
            </div>"; 
            $i++;
          }
          /* Restore original Post Data */
          wp_reset_postdata();
        }            
        ?>            
      </div>
    </div>