DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.

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):
      add_post_meta($post->ID, 'incr_number', $counts, true);
      update_post_meta($post->ID, 'incr_number', $counts);

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!



  1. How to make this function to give a permanent new id number even the post is deleted or set to draft?

  2. Awesome little function. Wish I had found this sooner. Thanks man.

Leave a Comment

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