I'm trying to create a permalink rule which is a few levels deep.
I have a basic page /page-slug/
- I'm appending to it a new endpoint: /page-slug/my-endpoint/
- from here I need to nest one id and one string that contain $_GET
variables, such as /page-slug/my-endpoint/?some_id=123&some_string=string
which should become: /page-slug/my-endpoint/123/string/
I got all the query vars successfully registered and I can grab them for use in my methods (e.g if I do var_dump( $wp_query->query_vars )
they will show up where set via $_GET
).
What I can't get to work is the rewrite rule to turn a URL in a pretty permalink (this snippet is run at init
hook time):
foreach ( $this->query_vars as $key => $var ) {
add_rewrite_endpoint( $var, EP_PERMALINK | EP_PAGES, $var );
if ( 'my-endpoint' == $key ) {
add_rewrite_tag( '%some_id%', '([^&]+)' );
add_rewrite_tag( '%some_string%', '([^&]+)' );
$page_id = get_some_page_id();
$page_slug = get_post( $page_id )->post_name;
// e.g. /page-slug/my-endpoint/123/some-string/
add_rewrite_rule(
"{$page_slug}/{$var}/([^/]*)/([^/]*)/?$",
'index.php?page_id=' . $page_id . '&some_id=$matches[1]&some_string=$matches[2]',
'top'
);
}
}
I tested the regex and does not look wrong, it catches what I need (123
and some-string
).
Up to 'page-slug/'
and also 'page-slug/my-query-var/
(2 levels deep) it works just fine, it's the two rewrite tags that don't work when used in a pretty permalink structure.
I tried with https://wordpress.org/plugins/monkeyman-rewrite-analyzer/ and the rules show up there - but I'm not sure about their interpretation
/page-slug/my-endpoint/123/some-string
and check forisset( $wp_query->query_vars['some_id'] )
it returns false (but no 404), if I do the same with/page-slug/my-endpoint/?some_id=123&some_string=some-string
it returns true%
in the 2ndadd_rewrite_tag
is a typo here? I can't test your code exactly, since parts are missing, but if I hardcode a page slug and endpoint name in the rewrite rule, it works for me.