07/02/2016   Comments Off on Automatically number each post in WordPress

View all snippets

In some cases I need to automatically number each post starting with the very first being number one. I’m not talking about using post ID here, but actual number in order of post date. Here’s the code I found that will work with any post type. Notice the post type I’m number is “podcast.” Change that to whatever post type you want to number. Add the below code to your functions.php file.

function updateNumbers() {
 /* numbering the published posts, starting with 1 for oldest;
 / creates and updates custom field 'incr_number';
 / to show in post (within the loop) use <?php echo get_post_meta($post->ID,'incr_number',true); ?>
 / alchymyth 2010 */
 global $wpdb;
 $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts 
 WHERE $wpdb->posts.post_status = 'publish' 
 AND $wpdb->posts.post_type = 'podcast' 
 ORDER BY $wpdb->posts.post_date ASC";
 $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', 11 );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );

Add the following highlighted function to your theme files where you want the number to display. For example:

<h1>Episode <?php echo get_post_meta($post->ID,'incr_number',true); ?>: <?php the_title();?></h1>

After this, update a post to see the numbers added to each post. If you don’t update one post, you will not see the changes until the next time you edit or publish a post.