1

I'm trying to create a new endpoint using add_rewrite_endpoint(). Here's my code:

// Add query var.
add_filter( 'query_vars', function( $vars ) {
    $vars[] = 'my-endpoint';
    return $vars;
} );

// Add endpoint.
add_action( 'init', function() {
    add_rewrite_endpoint( 'my-endpoint', EP_AUTHORS );
} );

I can now visit example.com/author/my-endpoint which is great but "sub" endpoints also seem to work. For example:

  • example.com/author/my-endpoint/random
  • example.com/author/my-endpoint/anything-here

How can I create my endpoint without also creating these "sub" endpoints?

1

The rewrite rule added by:

add_rewrite_endpoint( 'my-endpoint', EP_AUTHORS );

is

author/([^/]+)/my-endpoint(/(.*))?/?$

=>

index.php?author_name=$matches[1]&my-endpoint=$matches[3]

so it assumes anything after e.g. /author/henrywright/my-endpoint/....

You can try instead to replace it with add_rewrite_rule() e.g.

add_rewrite_rule( 
    '^author/([^/]+)/my-endpoint/?$', 
    'index.php?author_name=$matches[1]&my-endpoint=1', 
    'top'
);
  • 1
    add_rewrite_rule() seems far more flexible. Thanks for sharing this solution. – henrywright May 22 '17 at 16:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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