The issue with your desired structure is that adding a rewrite rule to intercept anything appended to a page URL will override and break child pages. In your example:
www.example.com/page-name/example
is example
a section, or a child page of page-name
? It’s not so simple to accommodate both cases.
A very quick and easy solution to this is to add something unique in the middle of the URL to signal a section rather than a child page. This can be done via add_rewrite_endpoint
, and WordPress will take care of generating the proper rewrite rules to make it work.
function wpa_rewrite_endpoint(){
add_rewrite_endpoint( 'section', EP_PAGES );
}
add_action( 'init', 'wpa_rewrite_endpoint' );
Now any level of page can have section/section-name/
appended, for example:
www.example.com/page-name/section/example/
or:
www.example.com/page-name/child-page-name/section/example/
and that value can then be accessed via get_query_var
:
$this_section = get_query_var( 'section' );
EDIT
Another possible, similar, option, depending on your requirements- If all of your section names are fixed, for example, there are only 3 potential sections: introduction
, body
, and conclusion
, you can use add_rewrite_endpoint
for each and instead name them the names of the sections:
function wpa_rewrite_endpoint(){
add_rewrite_endpoint( 'intro', EP_PAGES );
add_rewrite_endpoint( 'body', EP_PAGES );
add_rewrite_endpoint( 'conclusion', EP_PAGES );
}
add_action( 'init', 'wpa_rewrite_endpoint' );
You can then have URLs:
www.example.com/page-name/intro/
www.example.com/page-name/body/
www.example.com/page-name/conclusion/
Determining what section is loaded is a bit different here though, as you now don’t have anything for the value of your query vars, they’re all empty, so you’ll have to check if they exist in the array of query vars.
if( array_key_exists( 'intro', $wp_query->query_vars ) ){
echo 'intro requested!';
}