Support » Plugins » Hacks » Displaying parent post data in subpages

  • Resolved Ned Zimmerman


    I’m working on a site that has a custom post type called ‘Projects.’ The site design calls for each project to have two subpages (http://site-url/projects/project-name/about and http://site-url/projects/project-name/outputs which show a little more detail on different aspects of the project.

    Here’s the trick: I need to do this without having to create dummy child posts for each project. Is there a way to create different templates for each subpage and use a URL rewrite to display the same post via the subpage templates at /about and /outputs respectively?

    Thanks in advance. Hope the question makes sense.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You can indeed do this using a little bit of rewrite trickery

    I’ll be using the example of recipes (and have a dummy subpage called ingredients). You can then change it to fit your exact needs, but this should get you off in the right direction.

    First, you need to add the rewrite rules:

    add_filter('fnw_recipe_rewrite_rules', array($this, 'filter_recipes'));

    In this case, fnw_recipe is the alias for my CPT
    The method it calls is:

    public function filter_recipes($rules) {
    	$new = array(
    		'recipe/([^/]+)/ingredients?$'	=>'index.php?fnw_recipe=$matches[1]&fnw_recipe_page_type=ingredients'
    	return array_merge($new, $rules);

    We then need to add an extra query variable so we know what sub page we’re on:
    Add the following filter and method

    add_filter('query_vars', array($this, 'add_query_vars'));
    public function add_query_vars($vars) {
    	$vars[] = 'fnw_recipe_page_type';
    	return $vars;

    And lastly, so as to prevent WP redirecting to the parent, as the sub page doesn’t actually exist, add the following:

    add_action('wp', array($this, 'prevent_canonical_redirect'));
    public function prevent_canonical_redirect() {
    	if(get_query_var('fnw_recipe_page_type') == 'ingredients') remove_filter('template_redirect', 'redirect_canonical');

    And then you can use the collowing check in your template files to check which page you’re on (parent or a specific sub page)

    if(get_query_var('fnw_recipe_page_type') == 'ingredients') {
    	// Specific sub page
    } else {
    	// Top level page

    Regardless of if you’re in the top level or sub page, they all refer to the same post object, so you can access the content, post ID (and therefore custom post meta)

    Hope this helps, let me know if you have any issues

    Thanks, Damian! That’s exactly what I was looking for. I’ll give it a try and let you know if I run into any difficulties.

    Okay, it worked— had to tweak it a bit but now all’s well! Thanks for the tip about the canonical redirect. That was the piece of the puzzle I was missing.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Displaying parent post data in subpages’ is closed to new replies.