I have a custom post type mycpt
and I'm trying to allow for a variable to be appended onto the end of the URL right after the post name slug, like this:
www.site.com/mycpt/the-name-of-my-post/var-value-here/
I've been searching around, and the only examples I can find don't use the post name/slug in the URL, but rather taxonomies, so I'm not sure what the correct way to do it is. Here is what I'm trying now, but it's treating the URL with the variable as a separate page type (it's loading a default template rather than the template my custom post type uses).
add_action( 'init', function() {
add_rewrite_tag( '%my_var%', '([^/]*)' );
add_rewrite_rule( '^mycpt/(.*)/([^/]*)/?', 'index.php?post_type=mycpt&my_var=$matches[1]', 'top' );
}, 10, 0 );
I also tried changing $matches[1]
to $matches[2]
since I thought maybe the wildcard for the post name/slug was the first match, but that didn't work either.
Can anybody see what I'm doing wrong here?
my_var
in your rewrite rule.&p=xxx
url parameter? I figured WordPress automatically added that, since none of the examples I found added that parameter.p
, it's whatever your post type slug is,mycpt
in your example. Rewrite rules need to set all the necessary query vars to result in a successful main query.add_rewrite_endpoint
and having a variable name in the permalink structure.