Nov12

WordPress 代码实现子分类使用父分类模板(亲测可用)

wplogo-4

一般情况,无论是父分类还是子分类,我们如果要单独设置模板,都得新建一个:category-name.php,有没有一次搞定的呢,子分类直接使用父分类模板?

答案是有的。请把一下代码复制到function.php,别忘了<?php ?>

//方法一:
function myTemplateSelect() {
if (is_category() && !is_feed()) {
if (is_category(get_cat_id(‘name’)) || cat_is_ancestor_of(get_cat_id(‘name’), get_query_var(‘cat’))) {
load_template(TEMPLATEPATH . ‘/category-name.php’);
exit;
}
}
}
add_action(‘template_redirect’, ‘myTemplateSelect’);

//方法二:亲测可用

function pu_parent_category_hierarchy()
{
$category = get_queried_object();
$templates = array();
// Add default category template files
$templates[] = “category-{$category->slug}.php”;
$templates[] = “category-{$category->term_id}.php”;
if ( $category->category_parent != 0 )
{
$parent = get_category( $category->category_parent );
if(!empty($parent))
{
$templates[] = “category-{$parent->slug}.php”;
$templates[] = “category-{$parent->term_id}.php”;
}
}
$templates[] = ‘category.php’;
return locate_template( $templates );
}
add_filter( ‘category_template’, ‘pu_parent_category_hierarchy’ );:
[/php]

参考文档:
http://www.paulund.co.uk/force-sub-categories-use-parent-category-templates

http://wordpress.stackexchange.com/questions/4557/how-can-i-make-all-subcategories-use-the-template-of-its-category-parent

Comments are closed.