How to use foreach loop in wordpress the right way?

Author Jiwan Thapa         Posted on 09 Sep, 2018         35265 Views        

In this article, I've explained how to use forach loop in wordpress in the right way and the reason it's needed in some cases.

Recently, I faced a situation with where I needed to retrieve the index of my array data and I struggled a lot to display the slider images for bootstrap carousel. I found out from wordpress documentation that $current_post would do the trick, so, I tried it. Here's the code.

<?php 
$args = array(
  'post_type' => 'post',
  'category_name' => 'slider',
);
$query = new WP_Query( $args );
if(have_posts()):
?>
  <div id="slider" class="carousel slide" data-ride="carousel"> 
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <?php while ( have_posts() ) : the_post(); ?>
        <li data-target="#carousel-example-generic" data-slide-to="<?= $query->current_post ?>" <?php echo ($query->current_post == 0 ) ? 'class="active"' : ''?>></li>
      <?php endwhile; ?>       
    </ol>      

    <div class="carousel-inner" role="listbox">
      <?php while ( have_posts() ) : the_post(); ?>
        <div class="item <?php echo ($query->current_post == 0 ) ? 'active' : ''?>"> 
          <?php the_post_thumbnail(); ?>
          <div class="carousel-caption">
             <?php the_title() ?>
          </div>
        </div>
      <?php endwhile; ?>
    </div>
  </div>
<?php wp_reset_query(); endif; ?>

Needless to say, I got index (-1) all the time and when searching for the solution, I found out that the index number will be negative outside the loop. But, would anybody tell me what I'm doing wrong in this piece of code? Here's the output.

<div id="slider" class="carousel slide" data-ride="carousel"> 
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="-1" ></li>
    </ol>      

    <div class="carousel-inner" role="listbox">
        <div class="item "> 
            <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
             <div class="carousel-caption">bca</div>
        </div>
        <div class="item "> 
            <div class="carousel-caption">video 1</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
    </div>
</div>

Needless to say, it wasn't the one I wanted or expected and with no item with class active and unwanted posts in the output I felt the need to use foreach loop in this section. Here's what I did initially.

<?php 
$args = array(
  'post_type' => 'post',
  'category_name' => 'slider',
);
$sliders = query_posts( $args );             
if(have_posts()):
?>
  <div id="slider" class="carousel slide" data-ride="carousel"> 
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <?php foreach ($sliders as $key => $post):?>
        <li data-target="#carousel-example-generic" data-slide-to="<?=$key?>" <?php echo ($key == 0 ) ? 'class="active"' : ''?>></li>
      <?php endforeach; ?>       
    </ol>      

    <div class="carousel-inner" role="listbox">
      <?php foreach ($sliders as $key => $post):?>
        <div class="item <?php echo ($key == 0 ) ? 'active' : ''?>"> 
          <?php the_post_thumbnail(); ?>
          <div class="carousel-caption">
             <?php the_title() ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
<?php endif; ?>

What I did in this piece of code was in fact simply stored the array data that were retrieved from the WP_Query() in a variablenamed $sliders and then run the foreach loop which would make the case easy to check for array index and run the code properly. Here's the output then.

<div id="slider" class="carousel slide" data-ride="carousel"> 
    <!-- Indicators -->
    <ol class="carousel-indicators">
        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
        <li data-target="#carousel-example-generic" data-slide-to="1" ></li>
        <li data-target="#carousel-example-generic" data-slide-to="2" ></li>
    </ol>      

    <div class="carousel-inner" role="listbox">
        <div class="item active"> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
        <div class="item "> 
          <img width="" height="" src="..." alt="" />          
          <div class="carousel-caption">some captions</div>
        </div>
    </div>
</div>

That produced the perfect output I wanted but for some unknown reasons it was retrieving some other posts too in some cases. So, I did a bit more research and found out that adding setup_postdata($post) after the foreach loop did wonder to stabilize the result. Basically, it stores the retrieved data using the WP_Query in global variable $post. And we can use get_posts($args) in place of query_posts($args) as well.

So, here's the right code to use foreach loop is wordpress.

<?php 
$args = array(
  'post_type' => 'post',
  'category_name' => 'slider',
);
$sliders = get_posts( $args );             
if(have_posts()):
?>
  <div id="slider" class="carousel slide" data-ride="carousel"> 
    <!-- Indicators -->
    <ol class="carousel-indicators">
      <?php foreach ($sliders as $key => $post) : setup_postdata( $post )?>
        <li data-target="#carousel-example-generic" data-slide-to="<?=$key?>" <?php echo ($key == 0 ) ? 'class="active"' : ''?>></li>
      <?php endforeach; ?>       
    </ol>      

    <div class="carousel-inner" role="listbox">
      <?php foreach ($sliders as $key => $post) : setup_postdata( $post )?>
        <div class="item <?php echo ($key == 0 ) ? 'active' : ''?>"> 
          <?php the_post_thumbnail(); ?>
          <div class="carousel-caption">
             <?php the_title() ?>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </div>
<?php endif; ?>

Hence, using foreach loop in wordpress the right way helped me get my job done. Let everybody know via comments if you know some other ways to do it or you can simply register with your email address as an author and write your piece of blog to help others.


1 Like 0 Dislike 1 Comment Share


Julia Davis

13 May, 2023

The loop is typically used in WordPress themes to display blog posts, archive pages, search results, and other types of content. It works by iterating through a collection of posts and displaying them one by one, in accordance with the specified parameters. The loop can be customized using various WordPress functions and template tags to control the display of content, such as limiting the number of posts, displaying specific categories, or displaying the post author. Overall, the loop is an essential element of WordPress development and plays a critical role in how content is displayed on a website. These are some things which I want to include in your blog post. Readers, If you are confused about your wordpress website, you can take a free consultation from a company like Alakmalak technologies. They have 17+ years of experience in this field.

Reply


Leave a comment