Skip to content

Snippets / PHP

PHP

Change profile slug from display name to author id

G Gabi Maftei · 166 views · Updated 1 year ago
As described below. Please use it carefully. Backup your site first !
Change profile slug from display name to author_id (eg: site/profile/johnsmith/ to site/profile/122/) 1. Backup your site 2. Add the following php code to child theme functions.php file or using a code snippets plugin. 3. Go to Settings > Permalinks > Press Save changes twice.
function custom_author_rewrite_rules() {
add_rewrite_rule('^profile/([0-9]+)/?$', 'index.php?author=$matches[1]', 'top');
}
add_action('init', 'custom_author_rewrite_rules');

function change_author_link_to_id($link, $author_id, $author_nicename) {
return home_url('/profile/' . $author_id);
}
add_filter('author_link', 'change_author_link_to_id', 10, 3);

function redirect_old_author_slug_to_id() {
if (is_author()) {
$author = get_queried_object();
$current_url = home_url($_SERVER['REQUEST_URI']);
$correct_url = home_url('/profile/' . $author->ID);

if (trailingslashit($current_url) !== trailingslashit($correct_url)) {
wp_redirect($correct_url, 301);
exit;
}
}
}
add_action('template_redirect', 'redirect_old_author_slug_to_id');
PHP · 23 lines

Discussion

Ask a question or share how you used this.

Log in to join the discussion.

No comments yet — be the first.

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.