How to get and display post’s “position” in the query?

I have a simple query: $query = new WP_Query('showposts=5'); that will obviously display 5 latest posts. Is there any way to be able to get post’s position in the query? By position I mean… $query has 5 posts, and I need to be able to display the number of a post in the loop. I don’t really know PHP but I’m assuming the $query is an array variable (?) with these 5 posts.

It’s gonna be used in the JavaScript slider thing, where for every post I display a link like <a href="#1"></a> and I need that number to be 2 for the second post, 3 for the third etc.

Read More

Hope that makes any sense and someone will be able to help me.

Thanks in advance,
Justine

Related posts

Leave a Reply

3 comments

  1. For more bulletproof behavior, I would create the anchor links using each post’s UID (using the_ID()), rather than by their position on the page.

    Additionally, you should be iterating through $query be using the loop, which you can do multiple times in a page. (Haven’t used WordPress in a while, this code may be a bit off but the concept is sound)

    <?php 
    
    // Create the Query
    $query = new WP_Query('showposts=5');
    
    if ($query->have_posts()) :
    
        // Create the Javascript slider thing
        while ($query->have_posts()) : $query->the_post();
            // Do stuff here
        endwhile; 
    
        // Display the posts
        while ($query->have_posts()) : $query->the_post();
            // Do stuff here
        endwhile;
    
    endif;
    
    ?>
    
  2. $query->current_post will give you the index of the current item in the loop. Also, $query->post_count gives you the total count of the items in the loop. That might be helpful as well.

  3. It’s not that hard (I copied the PHP-code of cpharmston):

    <?php 
    
    // Create the Query
    $query = new WP_Query('showposts=5');
    
    if ($query->have_posts()) :
    
        $i = 1; // for counting
    
        // Create the Javascript slider thing
        while ($query->have_posts()) : $query->the_post();
            // Do stuff here
            $i++; // make sure this is @ the end of the while-loop
        endwhile;
    
    
        $i = 1; // reset $i to 1 for counting
    
        // Display the posts
        while ($query->have_posts()) : $query->the_post();
            // Do stuff here
            $i++; // make sure this is @ the end of the while-loop
        endwhile;
    
    endif;
    
    ?>
    

    You can use $i for #1, #2 etc. Everytime the while-loop has come to the end, $i++ makes sure it increments with one (so after the first time $i = 2 etc.).

    Hope this helps 🙂 (I do think that cpharmston’s solution would be easier though).