Pretty URL with add_query_var

I’m trying to add a ‘sub post’ to each post on my site, eg

site.com/product-one/changelog
site.com/product-two/changelog
site.com/product-three/changelog

This is the code I’m using atm, which I found here somewhere:

global $wp,$wp_rewrite;
$wp->add_query_var('sub-page');
$wp_rewrite->add_rule('([^/]+)/(changelog)','index.php?pagename=$matches[1]&sub-page=$matches[2]', 'top');
$wp_rewrite->flush_rules(false);  // This should really be done in a plugin activation

This works fine if I browse to site.com/product-one?sub-page=changelog but if I goto site.com/product-one/changelog i just get redirected back to site.com/product-one

So I disabled the canonical redirect as a test using:

remove_filter('template_redirect', 'redirect_canonical');

site.com/product-one/changelog then doesn’t redirect but does return a 404 and site.com/product-one?sub-page=changelog still works.

Is there something I can change with my rewrite to make this work?

Note: I know I could do this easy with custom post types and I started to go down that route, but because the site is already using the %postname% permalink structure, I then wouldn’t be able to have the custom post type have that structure as well as the sites pages.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

add_rewrite_endpoint( 'changelog', EP_ROOT );

Will add the endpoint, changelog, which you can then check on template_redirect hook.

On match the query variables ( $wp_query->query ) array should contain key changelog containing whatever comes after the / in value. So for URL example.com/product1/changelog/5 you would have a query variable named changelog with the value 5.

If there is nothing after endpoint then variable will be present, but contain empty string. Note that get_query_var() won’t work for such use since it is hardcoded to return empty string if query var is not set at all.

It may be enough to simply check if a variable is present and if so, modify the query variables in the query hooks (such as pre_get_posts) and load your own sub-post with the changelog template.

You may also want to experiment with different permalink endpoint masks, e.g. EP_PAGES

References:


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x