Sequentially Number WordPress Posts

Glenn Glenn's Blog 0 Comments

With this WordPress Snippet you can add a Numerical Number to your WordPress Posts or Custom Posts. In this implementation we are creating a custom WordPress Loop and adding a sequential post number  1, 2, 3, 4 etc above the post title:-


<?php $loop = new WP_Query( array( 'post_type' => 'your_post_type', 'posts_per_page' => -1 ) ); ?>
<?php
$postNumber = 1;
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div class="single-post">
<h1 class="post-number"><?php echo $postNumber++; ?></h1>
<h1 class="post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></h1>
<div class="post-content"><?php the_excerpt(); ?> </div>
<?php edit_post_link(); ?>
</div>
<?php endwhile; wp_reset_query();?>

The numbering comes from the PHP variable ‘$postNumber’ and is automatically incremented on a post by post basis / loop.

Note in this case we are using a Custom Post Type so either replace ‘your_post_type’ or to use standard Posts then just add in ‘post’.

An alternative Approach

This can also be achieved with a Custom Field if your Custom Posts are already part of your Theme and you can’t edit the WordPress Loop. Add the following to your functions.php and be sure to update your posts for the Custom Field to update:-



<?php
// sequentially order posts / custom posts
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,'your_post_type',true); ?>
/ alchymyth 2010 */
global $wpdb;
$querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'expert_guides' ";
$pageposts = $wpdb->get_results($querystr, OBJECT);
$counts = 0 ;
if ($pageposts):
foreach ($pageposts as $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', 11 );
add_action ( 'deleted_post', 'updateNumbers' );
add_action ( 'edit_post', 'updateNumbers' );
?>

The above taken from WordPress Forums

About the Author
Sequentially Number WordPress Posts Sequentially Number WordPress Posts 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

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