wordpress - 检查当前帖子是否在父类别或其子类别中
问题描述
我有 200 多个类别,我需要能够检查当前类别(在 category.php 上)是否在父类别数组中。
我已经阅读了大量方法来检查帖子是否属于某个类别或子类别,或者一只猫是否是另一只猫的孩子或父母。但是我找不到任何关于检查当前猫是否在父类别数组中的 WP 函数或问题。
这是我要完成的工作:
- 父 1 (ID 1)
- 孩子 1 (ID 5)
- 孩子 2 (ID 6)
- 孩子 3 (ID 7)
- 孙子 1 (ID 8)
- 父 2 (ID 2)
- 父母 3 (ID 3)
- 父 4 (ID 4)
我需要做这样的事情:
IF( cat_is_child_of( array(1,2,3,4)) ):
Do something amazing
ELSE
The current category is NOT within any of the parent categories for the ID's given
ENDIF
有任何想法吗???
<?php if (
is_post_type_archive( 'inventory' )
|| get_post_type( get_the_ID() ) == 'inventory'
// check if category IS one of these parent cats
|| is_category(array( 25,28,124,297,298,299 ))
// ugly version of checking if this cat is SUB of any parent cats
|| cat_is_ancestor_of(25, get_query_var( 'cat' ))
|| cat_is_ancestor_of(124, get_query_var( 'cat' ))
|| cat_is_ancestor_of(297, get_query_var( 'cat' ))
|| cat_is_ancestor_of(298, get_query_var( 'cat' ))
|| cat_is_ancestor_of(299, get_query_var( 'cat' ))
):
?>
解决方案
经过大量搜索并且只提出了检查类别是否具有子类别的功能,帖子是否在(仅)子类别中,我遇到了一个具有有效功能的旧帖子:
if ( ! function_exists( 'post_is_in_a_subcategory' ) ) {
function post_is_in_a_subcategory( $categories, $_post = null ) {
foreach ( (array) $categories as $category ) {
// get_term_children() only accepts integer ID
$subcats = get_term_children( (int) $category, 'category' );
if ( $subcats && in_category( $subcats, $_post ) )
return true;
}
return false;
}
}
以及我如何使用它:
<?php if (
is_post_type_archive( 'inventory' )
|| get_post_type( get_the_ID() ) == 'inventory'
// in one of the parent cats?
|| is_category(array( 25,28,124,297,298,299 ))
// in ANY of the subcats?
|| post_is_in_a_subcategory( array( 25,28,124,297,298,299 ) )
):
?>
例如,原始功能在 Wordpress 法典中,但不在核心中。http://codex.wordpress.org/Function_Reference/in_category#Testing_if_a_post_is_in_a_descendant_category它已被删除!
推荐阅读
- django - 为什么我的模板没有从一个函数中获取视图数据?
- python - 熊猫:将数据框中的多列加到一个新列中
- pyspark - Pyspark 根据距离连接两个表
- ubuntu - 在 docker 中执行 apt-get update 时出现“解决‘archive.ubuntu.com’的临时故障”错误
- c - DbgView 如何捕获 DbgPrintEx 函数发送的内核调试消息?
- ruby - 将创建的测试文件放在哪里。Ruby 目录结构
- c# - 如何在 Unity、Unreal 等游戏引擎中或直接在 webXr 中实时导出从 Grasshopper、Rhino3d 分析的顶点颜色?
- javascript - 如何在新创建的 html 表行上调用 java 脚本
- rust - FFI 回调和段错误
- python - Python程序属性:错误模块'reader'没有属性'Reader'