有些分类的文章想单独设置一种模板,该怎么操作呢?比如有一个software分类,id是17
对于category的页面,可以直接新建一个category-software.php,在显示software的所有文章时wordpress会自动应用category-software.php. 但是对于一篇文章页面,使用的是single.php 这个办法就不好用了。
in_category
这时我们可以在single文件里判断
1 2 3 4 5 6 7 8 |
<?php if ( in_category('software') ) { include(TEMPLATEPATH . '/single-software.php'); } else { include(TEMPLATEPATH . '/single-all.php'); } ?> |
这样,属于分类software的文章会用single-software.php显示,而其他的文章会使用single-all.php显示。这两个文件都要放在single.h同目录下哦
包括子分类
in_category只能判断只属于某个分类的文章,而不能判断子分类。wordpress提供了一种解决办法
笨办法。。。列举所有子分类
把上个例子in_category()改为
1 |
if ( in_category( array( 'fruits', 'apples', 'bananas', 'cantaloupes', 'guavas') )) |
或者在functions.php里面添加一个函数用于判断是否属于某个分类的子分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
/** * Tests if any of a post's assigned categories are descendants of target categories * * @param int|array $cats The target categories. Integer ID or array of integer IDs * @param int|object $_post The post. Omit to test the current post in the Loop or main query * @return bool True if at least 1 of the post's categories is a descendant of any of the target categories * @see get_term_by() You can get a category by name or slug, then pass ID to this function * @uses get_term_children() Passes $cats * @uses in_category() Passes $_post (can be empty) * @version 2.7 * @link http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category */ if ( ! function_exists( 'post_is_in_descendant_category' ) ) { 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里使用
1 |
if ( in_category( 'fruit' ) || post_is_in_descendant_category( 11 ) ) |
其中第二个函数参数是分类的id
打开wordpress后台的分类,把鼠标放到一个分类上面,就可以看到分类id
自己写一个函数判断分类和子分类
www.lizus.com的博客上有一篇文章提供了一个函数可以同时判断某一文章是否归属于某分类或其子孙分类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//post_is_in_under_category //check if a post is under a category or categories; //In Single.php,second param no need; //first param is for cat id; function post_is_in_under_category( $cats, $_post = null ) { foreach ( (array) $cats as $cat ) { // get_term_children() accepts integer ID only $descendants = get_term_children( (int) $cat, 'category'); if (in_category( $cat, $_post ) || ($descendants && in_category( $descendants, $_post) ) ) return true; } return false; } |
将这个写进functions.h 就可以在single里使用
1 2 3 4 5 6 7 8 |
<?php if ( post_is_in_under_category(17) ) { include(TEMPLATEPATH . '/single-software.php'); } else { include(TEMPLATEPATH . '/single-all.php'); } ?> |
注意:这个函数的参数只能是id 是一个整数