wordpress给不同的分类分配不同的列表页和内容页模板

我们知道wordpress分类页面和文章页面的模板默认为category.php和single.php

根据不同的分类制作不同的分类页模板,使用in_category()判断分类id,然后指定模板,在category.php写入以下代码,在新建三个模板文件:category-product,category-product,category-product

<?php
if ( is_category(array( 2,3 )) ) { //多个栏目id
    get_template_part('category-product');
} elseif ( in_category( 7 )) {//单个栏目id
    get_template_part('category-case');
} else {//其他调用默认模板
    get_template_part('category-default' );
}
?>

也支持slug别名调用:

is_category('themes') //单个别名
is_category( array( 'themes','plugins','develop') )//多个别名

同理,详情页的模板根据分类ID指定,在single.php里填入以下代码,新建以下三个模板文件:single-product,single-case,single-default

<?php
if ( in_category(array( 2,3 )) ) {//多个栏目id
    get_template_part('single-product');
} elseif ( in_category( 7 )) {//单个栏目id
    get_template_part('single-case');
} else {//其他调用默认模板
    get_template_part('single-default');
}
?>

还有个最简单的方法,比如给分类id为2的分类指定模板,就直接一个模板category-2.php,文章页就是 single-2.php,这个方式仅限少量分类的指定,分类多的话还是用上面的批量指定比较好。

注意:分类页用 is_category(),内容页用in_category()