Grow your CSS skills. Land your dream job.

help creating counter variable

  • # January 5, 2013 at 12:18 am

    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; ?>

  • < ?php

    $counter++;

    endwhile;
    wp_reset_query();
    }

# January 5, 2013 at 12:45 am

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

Set the initial value *before* the loop begins:

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

# January 5, 2013 at 1:02 am

I don’t know what you mean by that

# January 5, 2013 at 1:05 am

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

# January 5, 2013 at 4:13 pm

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

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".