Skip to content

Instantly share code, notes, and snippets.

@scarstens
Last active December 16, 2015 14:28
Show Gist options
  • Save scarstens/5448561 to your computer and use it in GitHub Desktop.
Save scarstens/5448561 to your computer and use it in GitHub Desktop.
This is a WordPress function that will extend the "template heirarchy" so that you can also load child pages in your theme using the following syntax: page-{PARENTSLUG}-child-{CHILDSLUG}.php
<?php
//apparently no need for this... page-SLUG.php matches subpage slugs,
//only need this function if subpage slug conflicts occur
//Add this code to you themes functions.php file, or some other file.
//Next create your child page lets says "domain.com/resources/faq"
//Finally, create the php template page following the naming schema:
//page-PARENTSLUG-child-CHILDSLUG.php -> page-resources-child-faq.php
add_filter( 'page_template', 'enable_child_page_templates' );
function enable_child_page_templates( $page_template ){
global $wp;
$slugs = explode('/', $wp->request);
if(isset($slugs[0]) && isset($slugs[1])) {
$f = __dir__.'/page-'.$slugs[0].'-child-'.$slugs[1].'.php';
}
if (isset($f) && file_exists($f) )
return $f;
else
return $page_template;
};
@scarstens
Copy link
Author

if you try to use the $wp object outside of the filter, I suggest adding it to the "wp" action, since it doesn't build the global var until after that action runs.

@scarstens
Copy link
Author

I added an example into the comments to make a usage case very easy to understand.

@scarstens
Copy link
Author

apparently no need for this... page-SLUG.php matches subpage slugs, only need if subpage slug conflict occurs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment