I have child page templates that need to be automatically applied based on the parent template.
I'm wondering if there is anyway Wordpress handles this.
This is the solution I came up with. (in page.php)
<?php
//Check parent template
if ($post->post_parent != $post->ID )
{
//Get parent template filename
$parentTemplate = get_post_meta($post->post_parent,'_wp_page_template',true);
}
switch ($parentTemplate) {
case 'about.php':
get_template_part( 'child_templates/content', 'about-child' );
break;
default:
get_template_part( 'content', 'page' );
}
?>
Edit
Function to apply parent template to child pages.
function switch_page_template() {
global $post;
// Checks if current post type is a page, rather than a post
if (is_page()){
$ancestors = $post->ancestors;
if ($ancestors) {
$parent_page_template = get_post_meta(end($ancestors),'_wp_page_template',true);
$template = TEMPLATEPATH . "/{$parent_page_template}";
if (file_exists($template)) {
load_template($template);
exit;
}
} else {
return true;
}
}
}
add_action('template_redirect','switch_page_template');
Check if page is parent or child
function is_subpage() {
global $post; // load details about this page
if ( is_page() && $post->post_parent ) { // test to see if the page has a parent
return true; // return the ID of the parent post
} else { // there is no parent so ...
return false; // ... the answer to the question is false
}
}
The template looks like this now
<?php
/*
Template Name: About Us
*/
?>
<?php get_header(); ?>
<?php if (is_subpage()): ?>
<?php get_template_part( 'templates/content', 'about-child' ); ?>
<?php else: ?>
<?php get_template_part( 'templates/content', 'about-parent' ); ?>
<?php endif ?>
<?php get_footer(); ?>