Rewrite user profile URL to be human friendly

The first step is to add a query var so WordPress will recognize it and parse its value in rewrite rules.

function wpd_query_vars( $query_vars ) {
    $query_vars[] = 'users_filter_name';
    return $query_vars;
}
add_filter( 'query_vars', 'wpd_query_vars' );

Next, add a rewrite rule to capture the requests and set the users_filter_name:

function wpd_user_rewrite_rule(){
    add_rewrite_rule(
        '^user-profile/([^/]*)/?',
        'index.php?page_id=31848&users_filter_name=$matches[1]',
        'top'
    );
}
add_action( 'init', 'wpd_user_rewrite_rule' );

Don’t forget to flush rewrite rules after they change.

Then you can access the query var in the template and load that user:

if( $users_filter_name = get_query_var( 'users_filter_name' ) ){
    $user = get_user_by( 'slug', $users_filter_name );
    if( !empty( $user ) ){
        echo $user->ID; // your original users_filter value
    }
}

Leave a Comment