dd

wordpress检查页面是否归属特定分类函数:in_category()


【函数介绍】

in_category()函数的作用是检查当前或者指定页面是否归属于特定的分类目录,通常用于给不同的分类目录设置不同的文章模板。

【函数用法】
<?php in_category( $category, $_post ) ?>

【参数说明】

$category
参数$category(必需)一个或多个目录ID (integer)、名字或者slug (string), 或者一个数组。
$_post
(混合) (可选)文章ID活文章对象. 默认为当前查询的文章对象或ID.
默认: None

【示例】

指定不同的目录文章应用不同的模板:

<?php
if ( in_category(1) ) {
	include 'single-1.php';
} elseif ( in_category('seo') ) {
	include 'single-seo.php';
} else {
	// Continue with normal Loop
	if ( have_posts() ) : while ( have_posts() ) : the_post();
	// ...
}
?>

这里要注意的是,in_category()函数只能指定一级目录,如果该目录有子孙目录则无效。如”fruits”下还有子目录’apples’, ‘bananas’, ‘cantaloupes’, ‘guavas’,则需全部目录列出来:

<?php if ( in_category( array( 'fruits', 'apples', 'bananas', 'cantaloupes', 'guavas', /*etc*/ ) )) {
	// These are all fruits
}
?>

或者在functions.php添加post_is_in_descendant_category()函数代码:

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

然后你可以调用post_is_in_descendant_category()函数来指定某目录下的所有子孙目录的文章页都使用某个模板:

<?php if ( in_category( 'fruit' ) || post_is_in_descendant_category( 'fruit' ) ) {
	// These are all fruits…
}
?>

【源代码】

in_category() 位于 wp-includes/category-template.php.