4

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

6
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:

2
  • 1
    Got it working with add_rewrite_endpoint, thanks for the links :) Commented Oct 28, 2011 at 9:01
  • You used EP_NONE while I've seen other sources use EP_PERMALINK, could you please expand on choice of constant?
    – Rarst
    Commented Mar 4, 2013 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.