Through the years I have come across many strange and wonderful ways of adding a counter to the WordPress loop. Often we need to know what post the loop is busy with so that we can add some code to the start or end of a specific post in the main loop.

Recently I wanted to show a widget area after the first post in the main loop used on the blog page. I did want this widget area to appear after the first post but I wanted it to show on the first page of the blog pages only.

The easiest way to do this is by using the built-in $wp_query loop counter. There is no need for more variables or any setting of these variables. In my case the code looked as follows:

You will notice that the conditional statements make sure that the code will only fire on the first page of the blog pages. The count of this built-in loop counter starts at 0 and it is only changed at the end of the loop. This means that if you want to add something at the end of the first post you will check against 0. If you wanted this widget area to appear at the end of the second post you would check against the number 1 in the code.

Sometimes less is more. This little snippet is efficient and it gets the job done.

I do hope you can find a use for this somewhere. Thanks for visiting.

Write a Reply or Comment

Your email address will not be published. Required fields are marked *