How to use author id in post permalink

Currently, WordPress supports author name in the post permalink by using %author%.

Is it possible to add the author id to the permalink?

For example, changing this:

http://www.site.com/john/my-first-post

to this:

http://www.site.com/1/my-first-post

Where ‘1’ is the id of the author ‘john’.

1 Answer
1

You can do this with a couple of filters:

<?php

function wpse_112719_pre_post_link( $permalink, $post, $leavename ) {
    if ( strpos( $permalink, '%author%' ) !== false ) {
        $authordata = get_userdata( $post->post_author );
        $author_id = $authordata->ID;
        $permalink = str_replace( '%author%', $author_id, $permalink );
    }

    return $permalink;
}

add_filter( 'pre_post_link', 'wpse_112719_pre_post_link', 10, 3 );

function wpse_112730_add_rewrite_rules() {
    add_rewrite_rule(
        "([0-9]+)/(.*)",
        'index.php?name=$matches[2]',
        'top'
    );
}

add_action( 'init', 'wpse_112730_add_rewrite_rules' );

Now, go to Settings → Permalinks and set your permalinks settings to /%author%/%postname%/. Save your changes, and your links should be working accordingly. Let me know if you have any issues!

Leave a Comment