How to create an endpoint without creating sub endpoints?

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 Answer
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'
);

Leave a Comment