I'm working on a site and the owner wants to add the post number to the title of each blog post.
So the first post would be "1. Post Title", etc.
The only thing that's coming up on Google is finding the post ID in the Dashboard, or displaying the total number of posts on the site, or things like that. Not what I need.
Can anyone point me in the right direction? I'm using the Gutenberg editor and using the Twenty Twenty-Four theme.
I'm working on a site and the owner wants to add the post number to the title of each blog post.
So the first post would be "1. Post Title", etc.
The only thing that's coming up on Google is finding the post ID in the Dashboard, or displaying the total number of posts on the site, or things like that. Not what I need.
Can anyone point me in the right direction? I'm using the Gutenberg editor and using the Twenty Twenty-Four theme.
Share Improve this question asked Jan 19 at 4:45 Nathan BNathan B 1732 silver badges12 bronze badges 3- 1 on which page do you want to display these numbers ? – mmm Commented Jan 19 at 8:54
- Perhaps this could help you Automatically update the slug of a product when the title of the product is updated. You will have to adjust it to your needs. Both post type and also append post ID to the slug. – Richard Commented Jan 19 at 9:32
- You could write a function which count the number of posts and order them by ID or date before to display it wherever you want. Without a minimal code, Stack Overflow won't help you much. Good luck. – gael Commented Jan 19 at 10:38
2 Answers
Reset to default 0There are many ways to achieve this, but none are trivial.
The Gutenberg Cheat code
Make a server-side rendered block, and use $wp_query->current_post +1;
to get the index of the post inside the loop.
With CSS
Using counter()
, see :
How do I achieve automatic numbering for headings using css
Using filter
The worst way because you can't see the result in Gutenberg editor, but you can filter the core/post-template
block with the render_block
filter and replace the ul
html tag with ol
The better solution ?
The better solution is programming a custom block doing the same as the core/post-template with your addition. You can find the source here: https://github.com/WordPress/gutenberg/tree/trunk/packages/block-library/src/post-template
Here's what worked. Add to functions.php:
function add_post_number_to_title( $title, $id = null ) {
// Check if we're dealing with a post and not in the admin dashboard
if ( is_admin() || is_null( $id ) || get_post_type( $id ) !== 'post' ) {
return $title;
}
// Get all posts ordered by date
$all_posts = get_posts( array(
'post_type' => 'post',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'ASC',
'fields' => 'ids',
) );
// Find the position of the current post in the list
$post_number = array_search( $id, $all_posts ) + 1;
// Prepend the post number to the title
return $post_number . '. ' . $title;
}
add_filter( 'the_title', 'add_post_number_to_title', 10, 2 );