我有需要根据父模板自动应用的子页面模板。
我想知道Wordpress是否会处理这个问题。
这就是我想到的解决方案。(在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 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\');
检查页面是父页面还是子页面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
}
}
模板现在如下所示<?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(); ?>