0

In my homepage, I have 10 latest posts. I want to display numbers starting from 0-9 in each post. 0 1 2 3 4 5 6 7 8 9

2

As this is a presentational thing, I'd be inclined to use CSS (there are of course ways of doing it in PHP, and others may disagree.)

You'd make use of the counter-reset and counter-increment properties.

CSS counters can be applied to any element, not just ordered-lists (<ol></ol>) and added using pseudo-elements and you can control the starting number and how it is incremented (counters can even run in reverse.)

They have very high browser support (essentially IE8 and above, and anything else.)

Here's some code for the twentyfourteen theme:

.home .site-content {
    counter-reset: posts -1;
}

.home article {
    counter-increment: posts;
}

.home .entry-title:before {
    content: counter(posts) '. ';
}

Note:

  • Not compatible with pagination, as list will still start at 0 on subsequent pages
  • The counter has to have a unique name - "posts"
  • The counter is incremented for each <article> tag
  • You want the first item to be 0, so we have to start at minus 1, because the first article will increment it by 1
  • Only tested in latest Chrome and Firefox, but 97% global browser support as mentioned above
  • Thanks but I will not prefer to use your css way. I had thought so big about this, therefore it overshadowed my brain. actually I had found what I was looking for. – Marc P Gangmei Apr 9 '15 at 4:01
  • <?php $the_query = new WP_Query( 'post_type=post&posts_per_page=10' ); ?> <?php if ( $the_query->have_posts() ) : $i = 0; $post_id = get_the_ID(); while ( $the_query->have_posts() ) : $the_query->the_post(); ?> <?php echo $i; ?> <?php $i++; endwhile; endif; wp_reset_postdata(); ?> – Marc P Gangmei Apr 9 '15 at 4:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.