简体   繁体   中英

WordPress add_rewrite_rule for user login in URL

I'd like to be able to use a user's login name in my URL, and then grab it for use within the page template. Like this:

mywebsite.com/admin/users/user/{user_login}

I've tried the following, but the query_var doesn't get added to the query and the match is always stripped from the end of the URL, like this:

mywebsite.com/admin/users/user/login-name/ --> mywebsite.com/admin/users/user/

I know the rewrite is happening, because it successfully takes me to the "user" page, but I just can't seem to get the user login to come with it.

/* add query var */

function add_user_query_vars($query_vars){

    $query_vars[] = 'user_login';

    return $query_vars;

}

add_filter('query_vars', 'add_user_query_vars');

/* add rewrite rule */

function add_user_rewrite_rules($rules){

    $user_rules = array('admin/users/user/([a-zA-Z0-9\._-]+)/?$' => 'index.php?pagename=user&user_login=$matches[1]');

    $rules = $user_rules + $rules;

    return $rules;

}

add_filter('rewrite_rules_array', 'add_user_rewrite_rules');

Thanks!

How about doing it in an .htaccess file?

Add this to the .htaccess file in your DOCUMENT_ROOT

RewriteEngine On
RewriteRule ^admin/users/user/([^/]+)/? index.php?pagename=user&user_login=$1 [DPI,L]

This assumes that mod_rewrite is both installed and activated for htaccess files.

Figured it out!

You have to include the full page hierarchy in the pagename parameter. In my case, it is admin/users/user, so my rewrite looks like this, and after a flush of the rewrite rules, it is working as expected.

$user_rules = array('admin/users/user/([a-zA-Z0-9\._-]+)/?$' => 'index.php?pagename=admin/users/user&user_login=$matches[1]');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM