wordpress不同分类文章调用不同模板

风中赏雪 Wordpress Wordpress 2025-10-12 1,666 0

在一般的cms中都会可以设置不同的分类列表和不同的分类文章采用不同的模板,这样更为灵活自由,也是由于作为CMS需要配合各种需求的界面设计要求,一般的企业站、门户站等不同的分类采用不同的模板较多,或者几个类型的模板,这是非常必要的。

而在WP里,默认是只有一个模板为single.php的,这显然对于cms是不够用的。

那么我们怎么解决这个问题呢?

我们知道,当wordpress读取一篇文章,会调用single.php,那么我们在single.php中加入加入条件判断语句,最常用的是in_category()函数,可以判断文章在哪个分类下,调用哪个single模板,但in_category()有局限性,不能判断子分类和子分类以下的分类,而in_category()只能单一写死分类ID。

解决方法是让文章自行判断,配合post_is_in_descendant_category()函数,首先在模板文件function.php中加入以下代码:

function post_is_in_descendant_category( $cats, $_post = null )
{
foreach ( (array) $cats as $cat ) {
// get_term_children() accepts integer ID only
$descendants = get_term_children( (int) $cat, 'category');
if ( $descendants && in_category( $descendants, $_post ) )
return true;
}
return false;
}

然后,将single.php内容替换成:

<?php
// 获取当前文章的分类
$categories = get_the_category();
$category_ids = wp_list_pluck($categories, 'term_id');

// 检查分类条件
if ( in_category(array(1,2)) || post_is_in_descendant_category(array(1,2)) ) {
    include(get_template_directory() . '/single-1.php');
} elseif ( in_category(array(3,4,5)) || post_is_in_descendant_category(array(3,4,5)) ) {
    include(get_template_directory() . '/single-2.php');
} else {
    // 确保 single-3.php 文件存在,或者使用默认的 single.php
    if (file_exists(get_template_directory() . '/single-3.php')) {
        include(get_template_directory() . '/single-3.php');
    } else {
        include(get_template_directory() . '/single.php');
    }
}
?>

以上代码表示,如果分类ID1和分类ID1以下所有分类中的文章,将使用single-1.php的模板,如果分类2和分类2及其所有子分类文章,使用single-2.php模板,其他分类使用single-3.php模板。

不过还是觉得wordpress的对于CMS的主题有局限性,毕竟是BLOG嘛,需要指定ID,没有DEDECMS这样的方便,不过也是有办法可以扩展解决的。编写主题后台配置ID,变量传值也还不错。