treehouse : what would you like to learn today?
Web Design Web Development iOS Development

help creating counter variable

  • I am having an issue making a counter variable in a while loop. I am using wordpress. I have 7 pages. I need an id that runs from 1 to 7. I figured that since the query loops through all pages, that a counter would be easy to make but I am proving this to be false. So what I am trying to get would be this

    nav_1 nav_2 nav_3

    and so on.

    So I tried this $counter = 1; class="nav_<?php echo $counter ?>" $counter++;

    but all that gives me is nav_1 reapeated 7 times.

    Here is the full code

    $args = ( array( 'post_type' => 'page', 'posts_per_page' => 7)); if ( is_home() ) {

      $pageQuery = new WP_Query( $args );
    
      while( $pageQuery->have_posts()) : $pageQuery->the_post();
    
      $counter = 1; ?>  
    
      <li class="nav_<?php echo $counter; ?>"><a href="#!/page_about_us"><b><?php the_post_thumbnail(); ?></b><strong></strong><span><?php the_title(); ?></span></a></li><?php
    
      $counter++;
    
      endwhile;
      wp_reset_query(); 
    

    }

  • You're setting $counter to 1 for every loop.

    Set the initial value before the loop begins:

      $counter = 1;
      while( $pageQuery->have_posts() ){ /* etc. ...
    
  • I don't know what you mean by that

  • I figured it out. Thanks, that was the hint I needed

  • I'm glad you figured it out.

    If I was unclear and anyone else was wondering:

      <?php
      // broken:
      while( $i < 5 ){
          $i = 1; //<-- INSIDE loop!
          $i++;
          // this loop will run forever,
          // because, even though $i is incremented
          // at the end of each loop,
          // it's reset to 1 at the beginning of the next.
      }
    
      // fixed:
      $i = 1; //<-- OUTSIDE loop
      while( $i < 5 ){
          $i++;
          // this loop will stop after 5 iterations
          // (as expected).
      }