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

2016-07-12 06:10 622 5 条评论 龙笑天下
Dragon主题购买

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

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

值得注意的是:in_category()考虑只有一篇文章的类别被直接分配(检查类别在写/编辑文章面板),而不是指定类别的父分类(请看下面的重点:如果一篇文章在后代分类下)。

在循环内部,这个标签可以用来测试当前的文章;或在循环外的单篇文章请求。如果您指定你想要测试的那篇文章,可以在任何地方使用它。

用法

<?php in_category( $category, $_post ) ?>

参数

$category
(混合的)(必选的)一个或多个被指定分类 ID,分类别名或 slug,或一个数组。
默认: 无

$_post
(混合的)(可选的)文章,默认为在主循环内的当前文章或在主查询中的文章。
默认: 无

返回值

概述中已经说了这个函数是布尔函数,所以它返回的值要么是真(True),要么是假(False),某篇文章是否属于特定的分类。

举例

在循环内测试当前文章

in_category 函数通常用于主循环中,根据当前文章的类别采取不同的行动,例如:

< ?php
if ( in_category( 'internet' )) {
// 如果这篇文章属于 internet 分类,此处添加要执行的内容。
} elseif ( in_category( array( 'ec', 'tmt' ) )) {
// 如果这篇文章同时属于 ec 和 tmt 分类,此处添加要执行的内容。
} else {
// 添加默认动作,也可以不要。
}
?>

在循环外测试当前文章

如果你要实现一种功能,根据不同的分类调取不同的模板,不妨试试下面的这个示例吧。

< ?php
if (  in_category(1) ) {
include 'single-1.php';
} elseif ( in_category('ec') ) {
include 'single-ec.php';
} else {
include 'single-default.php';
}
?>

重点:测试如果一篇文章在后代分类下

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

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

但是每次你移去或添加任何水果类别,你都不得不编辑代码。

更灵活的方法是使用或适应下面定义的 post_is_in_descendant_category 函数(在使用它之前,你需要复制下面的自定义函数到一个模板,插件,或主题函数文件):一般把此代码放入主题函数文件 functions.php

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

然后可以跟 in_category()一起使用,调用 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。

「点点赞赏,手留余香」

还没有人赞赏,快来当第一个赞赏的人吧!

声明:本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

2016-06-28

2016-07-17

发表评论

表情 格式 贴图 链接 私密 签到
Dragon主题购买阿里云特价云服务器1核2G低至86元,N4共享型服务器3年仅需799元腾讯云特价云服务器1核2G 88元/年 2核4G3M688元/3年,更有千元代金券礼包免费领!
评论
正在努力加载中...
扫一扫二维码分享
×
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept”, you consent to the use of ALL the cookies. Learn more