How to use endpoint, but remove/rewrite endpoint base?

Question

I’ve been messing around with rewrites and query_var to generate some listings, for example:

  • ~/my-page/?my_var=1
  • ~/my-page/?my_var=2
  • ~/my-page/?my_var=3

After perusing StackExchange and the interwebs a bit, it seems that the overwhelming consensus is that add_rewrite_endpoint is the way to go. As such, I’ve implemented the following:

function wpd_add_my_endpoint(){
    add_rewrite_endpoint( 'my_var', EP_PAGES );
}
add_action( 'init', 'wpd_add_my_endpoint' );

This yields the following URIs based on the ones I mentioned previously:

  • ~/my-page/my_var/1
  • ~/my-page/my_var/2
  • ~/my-page/my_var/3

However, I would like to strip out the ‘endpoint base’ (or slug, not even sure what to call this exactly, in this question/example ‘my_var’), so that the URIs would be:

  • ~/my-page/1/
  • ~/my-page/2/
  • ~/my-page/3/

I’ve tried a bunch of different ways to do rewrites, but none to any avail, this is what I have so far, which isn’t working:

function setup_filter_rewrites(){
    add_rewrite_rule('my-page/([^/]*)/?', 'index.php?pagename=my-page&my_var=$matches[1]', 'top');
}
add_action( 'init', 'setup_filter_rewrites' );

Updated

My code in it’s entirety is now:

// Add Query Var
function add_query_vars_filter( $vars ){
    $vars[] = "my_var";
    return $vars;
}
add_filter( 'query_vars', 'add_query_vars_filter' );

// Add Endpoint
function wpd_add_my_endpoint(){
    add_rewrite_endpoint( 'my_var', EP_PERMALINK | EP_PAGES );
}
add_action( 'init', 'wpd_add_my_endpoint' );

// Add Rewrite
function setup_filter_rewrites(){
    add_rewrite_rule('^my-page/([0-9]+)/?', 'index.php?pagename=my-page&my_var=$matches[1]', 'top');
}
add_action( 'init', 'setup_filter_rewrites' );

With the above code, ~/my-page/my_var/1/ works, but ~/my-page/1/ returns a 404. (I have flushed permalinks)

Huge thanks in advance!

0
, , , Ryan Dorn 3 years 2020-05-29T12:10:39-05:00 0 Answers 107 views 0

Leave an answer

Browse
Browse