Skip to content

Instantly share code, notes, and snippets.

@pixeldevsio
Created December 10, 2021 20:01
Show Gist options
  • Save pixeldevsio/5756ac8f3ff29791a5acd8e29a98d9ce to your computer and use it in GitHub Desktop.
Save pixeldevsio/5756ac8f3ff29791a5acd8e29a98d9ce to your computer and use it in GitHub Desktop.
Create custom WordPress structure for parent child page templates.
<?php
add_filter(
'page_template',
function ($template) {
global $post;
if ($post->post_parent) {
// get top level parent page
$parent = get_post(
reset(array_reverse(get_post_ancestors($post->ID)))
);
// or ...
// when you need closest parent post instead
// $parent = get_post($post->post_parent);
// $parent->post_name is the slug of the parent. This is your folder structure inside your theme
$child_template = locate_template(
[
'page-templates/' . $parent->post_name . '/page-' . $post->post_name . '.php',
'page-templates/' . $parent->post_name . '/page-' . $post->ID . '.php',
'page-templates/' . $parent->post_name . '/child.php',
]
);
if ($child_template) return $child_template;
} elseif (file_exists(get_stylesheet_directory() . '/page-templates/' . $post->post_name . '/page.php')) {
$parent_template = locate_template(
[
'page-templates/' . $post->post_name . '/page.php',
]
);
if ($parent_template) return $parent_template;
}
return $template;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment