Dynamically generate child-URLs for posts or custom posts

I just completed something like this (with great help from folks on this site).

First, you need to add the rewrite endpoint to your functions:

function wpa_read_endpoint(){
    add_rewrite_endpoint( 'sub-url', EP_PERMALINK);
}

add_action( 'init', 'wpa_read_endpoint' );

Make sure to then go to the permalinks section of admin and save to refresh permalink settings.

Then add some code to do some template switching dependent on query vars:

function wpa_read_template( $template="" ) {
    global $wp_query;
    if( ! array_key_exists( 'sub-url', $wp_query->query_vars ) ) return $template;

    $template = locate_template( 'templateFile.php' );
    return $template;
}
add_filter( 'single_template', 'wpa_read_template' );

A couple notes:

  • Refer to add_rewrite_endpoint info for different ‘places’ (in this case ‘EP_Permalink’), I was doing pages so it needed to change. (http://codex.wordpress.org/Rewrite_API/add_rewrite_endpoint)
  • Any changes you make to the add_rewrite_endpoint code will need to be refreshed by going back to the permalinks section in Admin.
  • When adding the template filter (add_filter) make sure you note the correct template ‘type’, in this case, single_template. Again I was using pages so it was page_template.

Good luck!