最近自己在修改一个采用Wordpress程序的博客的时候需要用到一个特殊的功能:我需要判断这篇文章是属于哪些分类,如果属于我设定的分类下的文章,则输出一个DIV内容。按道理说实现这个功能应该不算太难,因为印象中wordpress有相关的函数。简单查阅了一些资料后发现is_category和in_category这两个函数,最后是靠in_category函数实现的。具体方法也很简单:

in_category(array( ’1′, ’2′, ’3′)) ) 这段函数的意思是识别分类目录ID为1、2、3这三个分类,可以利用这个功能实现特定分类使用自定义模板或内容等。

这其中还有个小插曲让我纠结了很久,那就是in_category和is_category的差别,它们的差别让我想实现的功能差点就黄掉了。这里贴出来做个记录:

in_category:判断当前文章或指定文章是否属于某个指定类别,只有直属的类别,不包括直属类别的父辈类别;可以在循环内使用,也可以独立使用。

is_category:判断是否正在显示一个类别归档页面。

也就是说,如果你要在wordpress里面判断某个东西是否属于某分类,则用in_category,而如果是想判断某个分类的表现,那就要用is_category函数。

Examples

Testing the current post within the Loop

in_category() is often used to take different actions within the Loop depending on the current post's category, e.g.

<?php
if ( in_category( 'pachyderms' )) {
// They have long trunks...
} elseif ( in_category( array( 'Tropical Birds', 'small-mammals' ) )) {
// They are warm-blooded...
} else {
// & c.
}
?>

Testing the current post outside the Loop

During a request for an individual post (usually handled by the single.php template), you can test that post's categories even before the Loop is begun.

You could use this to switch templates like so:

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

(The Custom Post Templates Plugin allows for creation of templates for single posts. It also shows an example of how to add a template which is used for all posts in a given category, not just a single post. That example is commented out in the plugin by default but can be easily implemented by uncommenting the appropriate lines.)

Testing if a post is in a descendant category

When showing a category archive, or showing a category's posts via WP_Query() or get_posts(), or when hooking into the main query using is_main_query(), WordPress retrieves posts from the specified category and any descendant (child) categories, but in_category() tests only against a post's assigned categories, not ancestors (parents) of those categories.

For example, if you have a post assigned to the subcategory Fruit → Bananas and not the category Fruit, the Fruit category archive will show the "Bananas" post, but callingin_category('fruit') for that post always returns false.

You can list both the ancestor category and every possible descendant category, e.g.,

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

but you'd have to edit the code every time you moved or added any of the "Fruit" categories.

A more-flexible method is to use or adapt the post_is_in_descendant_category function defined below (you need to copy the function definition below into a template, plugin, or theme functions file before calling it). You can use it together with in_category() like this (in this example 11 is the "Fruit" category's ID number):

 // Post is assigned to "fruit" category or any descendant of "fruit" category?
<?php if ( in_category( 'fruit' ) || post_is_in_descendant_category( 11 ) ) {
// These are all fruits…
}
?>

If you'd rather refer to the category by name you can use, e.g.,

if ( $category_to_check = get_term_by( 'name', 'fruit', 'category' ))
post_is_in_descendant_category($category_to_check->term_id);

post_is_in_descendant_category function

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

WordPress教程之判断文章所属分类函数in_category、is_category的更多相关文章

  1. wordpress教程之文章页single.php获取当前文章所属分类

    之所以要发这篇文章,是因为这个方法适用于: WP默认文章分类 手动添加的自定文章分类 插件(custom post type ui)添加的自定义文章分类(含taxonomy) 方法目的:在文章模板中, ...

  2. python --- 19 判断对象所属,区分函数和对象, 反射

    一.判断对象所属 isinstance, type , issubclass 1.issubclass(x,y)    判断x是否是y 的子类 2.type(x)  精准返回x 的数据类型 3.isi ...

  3. wordpress获取文章所属分类

    1.获取全部分类 <?php foreach((get_the_category()) as $category){ echo $category->cat_name; } ?> 2 ...

  4. wordpress教程之函数讲解

    wordpress函数收集 is_home() : 是否为主页is_single() : 是否为内容页(Post),   是否是单篇文章  is_page() : 是否为内容页(Page),   是否 ...

  5. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数017·point点函数

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数017·point点函数 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“p ...

  6. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数015,vector矢量

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数015,vector矢量 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“p ...

  7. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数016,xld,xld轮廓

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数016,xld,xld轮廓 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“ ...

  8. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数014,tuple,元组

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数014,tuple,元组 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“p ...

  9. 《zw版·Halcon-delphi系列原创教程》 Halcon分类函数013,shape模型

    <zw版·Halcon-delphi系列原创教程> Halcon分类函数013,shape模型 为方便阅读,在不影响说明的前提下,笔者对函数进行了简化: :: 用符号“**”,替换:“pr ...

随机推荐

  1. itunes一进store就提示已停止工作该怎么解决

    改兼容,换盘重装什么的都试过了没用,可以听歌更新软件更改账号,但是就是进不了store,每次都是这个进度就卡死了. 问题事件名称: APPCRASH 应用程序名: iTunes.exe 应用程序版本: ...

  2. PowerShell_零基础自学课程_5_自定义PowerShell环境及Powershell中的基本概念

    PowerShell_零基础自学课程_5_自定义PowerShell环境及Powershell中的基本概念 据我个人所知,windows下的cmd shell除了能够通过修改系统参数来对其中的环境变量 ...

  3. 快速入门:触摸输入(使用 C#/VB/C++ 和 XAML 的 Windows 应用商店应用)

    原文 http://technet.microsoft.com/zh-cn/subscriptions/hh465387 快速入门:触摸输入(使用 C#/VB/C++ 和 XAML 的 Windows ...

  4. JAVA字符串转日期或日期转字符串

    文章中,用的API是SimpleDateFormat,它是属于java.text.SimpleDateFormat,所以请记得import进 来! 用法: SimpleDateFormat sdf = ...

  5. Pro Android 4 第六章 构建用户界面以及使用控件(一)

         目前为止,我们已经介绍了android的基础内容,但是还没开始接触用户界面(UI).本章我们将开始探讨用户界面和控件.我们先讨论一下android中UI设计的一般原理,然后我们在介绍一下an ...

  6. ulimit -c unlimited

    tomcat 产生core日志: app:/usr/local/apache-tomcat-7.0.55_8082/logs# ulimit -a core file size (blocks, -c ...

  7. 【剑指offer】面试题26:复杂链表的复制

    题目: 输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点). 思路: 复制自身到下一个结点: 设置新结点的random指针: 分离链表. 注意:判 ...

  8. 【转】NAT路由器打洞原理

    什么是打洞,为什么要打洞 由于Internet的快速发展 IPV4地址不够用,不能每个主机分到一个公网IP 所以使用NAT地址转换. 下面是我在网上找到的一副图 一般来说都是由私网内主机(例如上图中“ ...

  9. SPRING源码分析:IOC容器

    在Spring中,最基本的IOC容器接口是BeanFactory - 这个接口为具体的IOC容器的实现作了最基本的功能规定 - 不管怎么着,作为IOC容器,这些接口你必须要满足应用程序的最基本要求: ...

  10. 观察者模式与Boost.Signals

      1)  观察者模式定义 略,各种设计模式的书上都有定义. 2)  观察者模式一般实现 观察者模式一般实现,都是“被观察者”保存一个“观察者”的列表,循环这个列表来通知“观察者”.代码,其中使用了b ...