I created the rewrite rule

add_rewrite_rule("^user/(\d+)/(myaccount)/?", 'index.php?pagename=$matches[2]&user_id=$matches[1]','top');

So when a user visits example.com/user/123/myaccount/ it should use the wordpress page with slug 'myaccount' and pass '123' as the user_id.

I have flushed my rewrite rules, and I am using Monkeyman Rewrite Analyzer to check but it doesn't seem to match that pattern.

Can anyone point out what I'm doing wrong?

  • Try removing the brackets from (myaccount) and changing pagename in the URL to myaccount: add_rewrite_rule("^user/(\d+)/myaccount/?", 'index.php?pagename=myaccount&user_id=$matches[1]','top'); (Not tested, so not adding as an answer). Nov 29, 2017 at 3:56

2 Answers 2


I tested the suggestion from my comment and it worked.

Remove the brackets from (myaccount) and change $matches[2] in the URL to myaccount:

function wpse_287203_rewrite_rule() {
    add_rewrite_rule( '^user/(\d+)/myaccount/?', 'index.php?pagename=myaccount&user_id=$matches[1]', 'top' );
add_action( 'init', 'wpse_287203_rewrite_rule' );

(myaccount) will not match a whole world. That's a little more involved. See this Stack Overflow answer for how to match an exact word. We don't need to do that here though, since we can just manually put the word into the second argument of add_rewrite_rule().

Also, it wasn't part of the question, but it's what comes next. To get access to the user_id, you need to add it to the list of valid query variables:

function wpse_287203_query_vars( $vars ) {
  $vars[] = 'user_id';

  return $vars;
add_filter( 'query_vars', 'wpse_287203_query_vars' );

Now you can get the user id when on that URL with get_query_var():

$user_id = get_query_var( 'user_id' );
$userdata = get_userdata( $user_id );
  • it looks like there was another rule taking precedence (.?.+?)?(:/([0-9]+))?/?$ I changed my rule to: ^user/([^/]+)/myaccount/? and now I see it working, I also added the query_vars like you suggested Much help, thanks Jacob
    – Kyle Tripp
    Nov 29, 2017 at 20:59

Your rewrite rule user/(\d+)/(myaccount)/ had an error because of forward slashes. In regular expressions, "/" is a special character which needs to be escaped, which you can do by adding a backslash(/). So your rewrite rule may look something like this:


I hope this solves your issue.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.