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

销售前的奉承,不如售后服务。这是制造“永久顾客”的不二法则。那些花了好久才想明白的事,总是会被偶尔的情绪失控全部推翻。

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

首先在function.php里,添加如下代码:

1
2
3
4
5
6
7
8
9
10
11
//获取并输入某个分类的子分类
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;
}

//获取并输入某个分类的子分类 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(); 之外的所有内容改成:

1
2
3
4
5
6
7
8
9
10
11
12
13
<?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');
}//给其他分类的文章调用的。
?>

<?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 朋友注册的见面礼,所以就单独为文,多谢分享!

以上就是让WordPress不同的分类目录的文章调用不同的模板。如果你想得到,你就会得到,你所需要付出的只是行动。更多关于让WordPress不同的分类目录的文章调用不同的模板请关注haodaima.com其它相关文章!

您可能有感兴趣的文章
WordPress站点Gravatar头像前后台不显示的如何解决办法

WordPress主题需要支持https吗?WordPress站点如何如何实现https?

WordPress站点的页面/标签/分类URL地址如何添加.html?

WordPress站点更换了域名后数据库应该如何操作替换新旧域名?

WordPress安装在主机空间的什么目录里面?根目录在哪里?