Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 6 down vote accepted
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:

share|improve this answer
1  
Got it working with add_rewrite_endpoint, thanks for the links :) –  Adam Dempsey Oct 28 '11 at 9:01
    
Thanks for the accept =] –  Tom J Nowell Oct 28 '11 at 9:25
    
You used EP_NONE while I've seen other sources use EP_PERMALINK, could you please expand on choice of constant? –  Rarst Mar 4 '13 at 16:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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