Post Pic

How to display an incrementing number next to each published post

Ever wished to be able to automatically number your posts (Like Article 1, Article 2, and so on) like sites such as A List Apart are doing? If yes, just read this recipe which will show you how to do it easily.

The first thing to do is to paste the function into your functions.php file:

function updateNumbers() {
  global $wpdb;
  $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
  $counts = 0 ;
  if ($pageposts):
    foreach ($pageposts as $post):
      setup_postdata($post);
      $counts++;
      add_post_meta($post->ID, 'incr_number', $counts, true);
      update_post_meta($post->ID, 'incr_number', $counts);
    endforeach;
  endif;
}  

add_action ( 'publish_post', 'updateNumbers' );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Once done, you can display the post nimber by pasting the following on your theme file, within the loop:

<?php echo get_post_meta($post->ID,'incr_number',true); ?> 

Credits goes to WordPress forums for this very cool piece of code!

9 Responses

Apr 05 2010 16:37

what if I wanted this only from one category?

Apr 05 2010 17:32

It is good – maybe you should thank the actual person who wrote it in the forum?

Apr 05 2010 17:37

@David Hutchison: Sure, I’ll change the link to his website if he have one.

Apr 05 2010 22:56

not sure i like your sql, below would be easier to code and to read later

$querystr = “SELECT * FROM $wpdb->posts p
WHERE p.post_status = ‘publish’
AND p.post_type = ‘post’ “;

Apr 07 2010 15:38

Fantastic ! At last I’ll can display issues number for my webcomic.

Apr 08 2010 13:28

WOW. Your timing is eeringly good, been trying to figure this out for a couple of days now… W00t!

Aug 16 2010 19:29

This solution looks legit. Im going to give it a try…I am looking to create a theme for listing Top Ten Items.

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required