WordPress教程之判断文章所属分类函数in_category、is_category

2023-05-16

最近自己在修改一个采用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;
    }
}
?>  

 

转载于:https://www.cnblogs.com/huntaheart/p/3964646.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • httpclient4封装类与HttpParser封装类

    httpclient4封装类与HttpParser封装类 最近工作中需要做一个爬虫去抓取指定页面的一些内容 xff0c 准备使用HttpParser来解析页面结构 xff0c 顺便看了一下httpclient4 xff0c 可以将它们配合使
  • 【Linux操作系统分析】进程——进程切换,进程的创建和撤销

    1 进程 进程是程序执行时的一个实例 xff0c 可以把它看作充分描述程序已经执行到何种程度的数据结构的汇集 从内核的观点看 xff0c 进程的目的是担当分配系统资源 xff08 CPU时间 xff0c 内存等 xff09 的实体 xff0
  • C++中的.和::和:和->的区别

    在学习C 43 43 的过程中我们经常会用到 和 和 xff1a 和 gt xff0c 在此整理一下这些常用符号的区别 1 A B则A为对象或者结构体 xff1b 2 A gt B则A为指针 xff0c gt 是成员提取 xff0c A g
  • 通过Curl 对url进行encode操作

    最近做项目的时候 xff0c 通过 Gflags Reload 时候 发现对于某些value中包含 61 中文等字符的支持不够好 xff0c value被截断了 经过分析后 xff0c 发现程序对url切分是用 61 amp 为标准的 xf
  • STM32进阶之串口环形缓冲区实现(转载)

    转载自微信公众号 玩转单片机 xff0c 感谢原作者 杰杰 队列的概念 在此之前 xff0c 我们来回顾一下队列的基本概念 xff1a 队列 Queue xff1a 是一种先进先出 First In First Out 简称 FIFO 的线
  • 位和结构体寄存器访问方法(转)

    1 2 1 传统 define 方法 1 2 外设位域结构体方法综述 DSP281x 头文件和外设示例使用位域结构体方法 xff0c 映射和访问基于F28x 外设寄存器 本节将介绍这种方法 xff0c 并把它和传统的 define 方法加以
  • 关于将函数写入头文件问题(分离式编译)

    如果某些函数在其他很多 cpp 文件中被调用 xff0c 那么为了避免写大量重复的代码以及让代码量更小一些 xff0c 我们可以将这些函数写头文件中 xff0c 然后其他 cpp 文件只需要引用该头文件然后就可以使用包含在头文件中的函数了
  • SpringSecurity配置跨域访问

    说明 java后端web服务有很多种方法可以实现跨域访问 xff0c 配置很简单 xff0c 今天这里我们用SpringSecurity的方式配置跨域访问 xff0c 配置方法如下 xff1a span class token keywor
  • 嵌入式C语言开发---存储器与寄存器

    概述 xff1a 讲述如何使用C语言来对底层寄存器进行封装 内容 xff1a 存储器映射寄存器与寄存器映射C语言访问寄存器 存储器映射 程序存储器 数据存储器 寄存器和I O 端口排列在同一个顺序的4 GB 地 址空间内 存储器映射 xff
  • httplib用法

    httplib的内容上是很多 xff0c 也比较简单 以下是一个非常简单的例子 xff0c 使用httplib获取google首页的html xff1a import httplib conn 61 httplib HTTPConnecti
  • HTTP认证之摘要认证——Digest(一)

    导航 HTTP认证之基本认证 Basic xff08 一 xff09 HTTP认证之基本认证 Basic xff08 二 xff09 HTTP认证之摘要认证 Digest xff08 一 xff09 HTTP认证之摘要认证 Digest x
  • Linux 文件名和路径的最大长度

    在x86 64 Linux下 xff0c 文件名的最大长度是255个字符 characters xff0c 文件路径的最大长度是4096字符 characters xff0c 即可以包含16级的最大文件长度的路径 在 lt limits h
  • Django之auth

    一 xff1a auth基础 xff08 1 xff09 作用 xff1a django提供给开发人员 对用户进行操作的模块的 例如 xff1a 登录 注册 认证 注销等等 xff08 2 xff09 使用方式 from django co
  • [JavaSE 源码分析] 关于HashMap的个人理解

    目录 HashMap是什么 HashMap的底层数据结构是什么 table容量为什么必须是二的倍数 table容量怎么做到二的倍数 Entry是怎样的结构 Node Entry在HashMap中的具体实现处理hash冲突的方法HashMap
  • HIS(LIS、PACS、RIS、EMR)系统简介

    HIS xff08 LIS PACS RIS EMR xff09 系统简介 HIS xff1a 医院信息系统 Hospital Information System HIS xff0c 利用电子计算机和通讯设备 xff0c 为医院所属各部
  • jackson使用问题:mapper.readValue()将JSON字符串转反序列化为对象失败或异常

    问题根源 xff1a 转化目标实体类的属性要与被转JSON字符串总的字段 一 一对应 xff01 字符串里可以少字段 xff0c 但绝对不能多字段 先附上我这段出现了问题的源码 xff1a 1 接收并转化相应的参数 需要在pom xml中引
  • SpringSecurity集成oauth2(jwt)

    版本 springboot版本 xff1a 2 2 7 RELEASE spring security oauth2版本 xff1a 2 3 6 RELEASE 主要依赖 span class token tag span class to
  • 微信小程序开发——点击按钮获取用户授权没反应或反应很慢的解决方法

    异常描述 xff1a 点击按钮获取用户手机号码 xff0c 有的时候会出现点击无反应 或很久之后才弹出用户授权获取手机号码的弹窗 xff0c 这种情况下 xff0c 也会出现点击穿透的问题 xff08 详见 xff1a 微信小程序开发 连续
  • 09-cmake语法-add_dependencies()

    在编译器的命令行上 xff0c 为当前路径以及下层路径的源文件加入一些define flag 这个命令可以用来引入任何flag xff0c 但是它的原意是用来引入预处理器的定义 那些以 D或 D开头的 看起来像预处理器定义的flag xff
  • WordPress教程之判断文章所属分类函数in_category、is_category

    最近自己在修改一个采用Wordpress程序的博客的时候需要用到一个特殊的功能 xff1a 我需要判断这篇文章是属于哪些分类 xff0c 如果属于我设定的分类下的文章 xff0c 则输出一个DIV内容 按道理说实现这个功能应该不算太难 xf