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.

1 Answer
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:

  • Codex > Rewrite API and Codex > Rewrite API > add_rewrite_endpoint()
  • Rewrite enpoints API post by Jon cave
  • Monkeyman Rewrite Analyzer plugin for rewrite debug
  • Custom Post Type Permalinks post by ShibaShake (scroll down)

Leave a Reply

Your email address will not be published. Required fields are marked *