Search code examples
wordpress

How to add numbering to Wordpress post titles


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.


Solution

  • 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 );