• 首页
  • >
  • 让WordPress不同的分类目录的文章调用不同的模板
  • >
  • 正文

让WordPress不同的分类目录的文章调用不同的模板

138次阅读

近日,因为网站建设的需要,在没有使用自定义文章类型的情况下,使用不同的分类目录里的文章调用不同的模板,作为注册wordpress大学的见面礼。

首先在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,命名为:single-*.php文件名(你可以根据自己的需要,制作多个 single-*.php 文件,通过修改每个single-*.php 文件的html结构和添加对应的CSS,就可以实现不同的文章页面样式 )。

将 single.php 里面除了 get_header(); get_footer(); get_sidebar(); 之外的所有内容改成:

<?php
if ( in_category('16') || post_is_in_descendant_category(16) )//可自行修改 这里包含分类目录里的文章和分类目录里的子分类目录里的文章
{
  include(TEMPLATEPATH .'/single-16.php');
}
elseif ( in_category('7') || post_is_in_descendant_category(7) )//如果只有两类single.php,可以不要这段,如果是多类,则添加多个elseif
{
  include(TEMPLATEPATH . '/single-7.php');
}
else{
  include(TEMPLATEPATH . '/single-other.php');
}//给其他分类的文章调用的。
?>

倡萌注:该文章的方法和倡萌之前分享的《WordPress不同分类使用不同的文章模板》的方法二一样,就是使用 in_category() 函数来判断,不同的地方就是添加了自定义函数 post_is_in_descendant_category() 来获取某个分类的子分类。本来打算直接在之前的文章中更新的,但考虑到这是 @leon 朋友注册的见面礼,所以就单独为文,多谢分享!

作者:管理员  修订  2019/07/10 11:46:18

WP爱好者专注WordPress在线系统培训,10年来超过十万学员在此获得技术提升和人脉圈子。

WordPress课程已融入到移动搜索、零基础建站、WP爱好者开源主题模板、SEM入门等。

欢迎添加助教微信:tc199361,马上获得优秀学员案例。