Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End help creating counter variable

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #41761
    cybershot
    Participant

    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_"
    $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; ?>

  • wp_reset_query();
    }

#119878
__
Participant

You’re setting `$counter` to `1` for every loop.

Set the initial value *before* the loop begins:

$counter = 1;
while( $pageQuery->have_posts() ){ /* etc. …

#119926
__
Participant

I’m glad you figured it out.

If I was unclear and anyone else was wondering:

// 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).
}

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Back End’ is closed to new topics and replies.