WordPress: Get and Show the Post Position in the Loop

I needed to show the position of my posts in the loop. I did a lot of searching around the web for a solution, but the answers I found didnæt quite solve it for me.

They used a solution that only worked on page 1 of the archives. On pages 2,3,4, etc the position would always start on 1 again. Instead, I wanted to start on position 21 for page number 2 and on 41 for page number 3.

The below code solved this for me. It will work with any number of posts you set to display on each archive page in the WordPress setting.

The Code

if ( $wp_query->have_posts() ):
$position = 0;
while ( $wp_query->have_posts() ): $wp_query->the_post();
$curpage = (get_query_var('paged')) ? get_query_var('paged') : 1;
$postsperpage = get_option( 'posts_per_page' );
if($curpage > 1) {
$actualposition = $position + (($curpage - 1) * $postsperpage);
} else {
$actualposition = $position;
echo $position;

As you can see, you need to nest this code before the loop with $position = 0; and then start counting the position in the while loop with $position++;

Then some simple math will calculate the actual position of the post depending on which page you are on.