How to Group Posts by the First Letter or Number?

I think there’s a better approach, just create a custom taxonomy that holds the alphanumeric terms, then assign each post to the correct term.

You can use the save post action to auto assign posts to correct term on post save:

function save_index( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        return;
    }

    $slug   = 'post';
    $letter="";

    // only run for posts
    if ( isset( $_POST['post_type'] ) && ( $slug != $_POST['post_type'] ) ) {
        return;
    }

    // Check user capabilities
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        return;
    }

    $taxonomy = 'index'; // our custom taxonomy

    if ( isset( $_POST['post_type'] ) ) {

        // Get the title of the post
        $title = strtolower( $_POST['post_title'] );

        // The next few lines remove A, An, or The from the start of the title
        $splitTitle    = explode( ' ', $title );
        $blacklist     = [ 'an ', 'a ', 'the ' ];
        $splitTitle[0] = str_replace( $blacklist, '', strtolower( $splitTitle[0] ) );
        $title         = implode( ' ', $splitTitle );

        // Get the first letter of the title
        $letter = substr( $title, 0, 1 );

        // Set to 0-9 if it's a number
        if ( is_numeric( $letter ) ) {
            $letter="0-9";
        }

    // set term as first letter of post title, lower case
    wp_set_post_terms( $post_id, $letter, $taxonomy );
    }
}

add_action( 'save_post', 'save_index' );

Leave a Comment