Support » Plugins » Access the current loop count variable from plugin?

  • I could not find this info anywhere: Does WordPress have a global variable that would allow plugin developers to determine where WordPress is in the current loop display? So for instance if WordPress is displaying on the index and has 10 posts to display (because the admin set this in settings) and the loop is in the first post, is there a variable I can call like “$loopcount” from my plugin to determine when we’ve hit the third post? This would seem like a very smart and nice thing to have but I don’t know what it would be or can’t find info on it.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42) Admin


    global $wp_query;
    echo $wp_query->current_post;

    The first post is post zero.

    Similarly, $wp_query->post_count will give you a count of how many posts there are.

    When the Loop is actually running, in_the_loop() will return true.

    There’s also a few action hooks. The ‘loop_start’ action gets called on the first call to the_post(), and the ‘loop_end’ action gets called on the last post-getting invocation of have_posts(). Meaning that those run just before the loop starts and ends.

    Thank you very much, this is great. I actually know about the loop_start and loop_end parts and I use them in my plugins, but for some reason I was never able to find the post_count or current_post elements you mentioned above.

    Now one last major question:
    Does WordPress manage to keep a count of how many times the loop has been rewound on the same page? So if I have a page that goes through the loop once, then calls the rewind function to redo the loop, does this get notated anywhere that can be queried? Or does the action of rewinding the loop have some way of being detected? I’d love to be able to place something at the start of the first loop on a page, then be able to say “no, don’t show it at the start of any subsequent loop done on this same page rendering”

    Moderator Samuel Wood (Otto)

    (@otto42) Admin

    Not really, no. You could hook onto loop_start and make your own global to note that you’ve seen one Loop, and then if you see it a second time, you could behave differently. But it doesn’t keep a count or have anything special happening on rewinding.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Access the current loop count variable from plugin?’ is closed to new replies.