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

寒龙亦 2019-2-2 2061

利用wordpress 主题来搭建企业网站 的时候往往会遇到这种情况,新闻页面和产品页面需要用两种方式来显示,但wordpress只有一个single.php页面,这时就需要用到页面显示的判断方式来显示,也就是不同的分类显示不同的页面内容,这个对于企业建站 非常重要,下面给大家分享一个怎样在不同的分类下显示不同的内容。

1、首先在function.php函数文件中加入以下代码:

<?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;
}
?>

2、将single.php里面的内容全部替换成以下代码,注意是将single.php里面的所有代码全部替换:

<?php 
if ( in_category('1') || post_is_in_descendant_category( 1) ){
include(TEMPLATEPATH .'/single1.php');
}
elseif( in_category('2') || post_is_in_descendant_category( 2 ) ){
include(TEMPLATEPATH . '/single2.php');
}else{
include(TEMPLATEPATH . '/single3.php');
}
?>

3、在主题目录中创建3个single.php文件,分别取名为:single1.php、single2.php、single3.php,当然你也可以自定义这些文件的名字,再修改一下single.php代码里对应的名字即可。

single.php代码的意思是:分类目录的ID1及以下所有分类的文章,用single1.php页面模板来显示,分类目录的ID2及以下所有分类的文章,用single2.php页面模板来显示,其他分类用single3.php页面模板来显示。

至于分类的ID需要跟据自己的分类目录ID来修改。


最新回复 (0)
全部楼主
返回