Maarten Wolfsen
Maarten Wolfsen

Reputation: 1733

Get the current post number (not ID) in wordpress

I am using this function to get the amount of posts:

$postAmount = wp_count_posts( 'post' )->publish;

This returns 4, which is the right number. But, is there also a function, where I can check the current post number? Not the ID, but only a number.

For example, I am at the second post, so I want the function to return '2'.

Extra information

$wp->query->current_post+1 returns 0 at every post

Upvotes: 1

Views: 6892

Answers (2)

Samir Sheikh
Samir Sheikh

Reputation: 2401

use $wp_query->current_post + 1 instead of $wp->query->current_post+1

full code like..

<?php

$postArg = array('post_type'=>'post',
                        'posts_per_page'=>-1,
                        'order'=>'desc',
                      );
        global $post;
        $getPost = new wp_query($postArg);
            if($getPost->have_posts()){
            echo '<ul>';
                while ( $getPost->have_posts()):$getPost->the_post();   

                     $index= $getPost->current_post + 1;
                     echo "<h2>".$post->post_title."</h2>".$index;

                endwhile;
            echo '</ul>';
        }

?>

Upvotes: 0

Tulio Troncoso
Tulio Troncoso

Reputation: 306

You've got the right idea, but just made a small typo. What you want is

$wp_query->current_post

or

$wp_query->current_post + 1

depending on wether or not you want to count starting at zero.

enter image description here

Search for current_post in the WP_Query Codex https://codex.wordpress.org/Class_Reference/WP_Query

Upvotes: 5

Related Questions