add_rewrite_rule for custom sub pages

For a plugin I need a subpage of a regular WordPress page. The normal page is located at

http://example.com/page

To get a subpage

Read More
http://example.com/page/subpage

I’m using the rewrite_rule:

add_rewrite_rule( '([^/]+)/(subpage|subpage2|subpage3|subpage4)', 'index.php?pagename=$matches[1]&_mysubpage=$matches[2]', 'top');

This is working fine until I move the page to a parent page:

http://example.com/parentpage/page/subpage

or if I set the page as homepage

http://example.com/subpage

Which additional add_rewrite_rule do I need?

Related posts

Leave a Reply

1 comment

  1. I found a working solution but if anyone have a better feel free to share.

    1) The Subpage

    The pagename on a subpage is page/subpage so the initial add_rewrite_rule become

    add_rewrite_rule( '(.+)/(subpage|subpage2|subpage3|subpage4)', 'index.php?pagename=$matches[1]&_mysubpage=$matches[2]', 'top');
    

    2) The Homepage

    For the homepage you need the ID of the page and an additional add_rewrite_rule

    add_rewrite_rule( '^(subpage|subpage2|subpage3|subpage4)', 'index.php?page_id={YOUR_PAGE_ID}&_mysubpage=$matches[1]', 'top');
    

    note that pagename get’s replaced with page_id