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

来源:互联网 发布:js返回true false 编辑:程序博客网 时间:2024/06/09 15:46

近日,因为网站建设的需要,在没有使用自定义文章类型的情况下,使用不同的分类目录里的文章调用不同的模板,作为注册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() 来获取某个分类的子分类。

如果有更多的技术技巧分享也请在www.diandian100.cn联系我,谢谢大家的分享

0 0
原创粉丝点击