如何扩展此函数来检查当前自定义帖子类型是否属于后代类别

发布于 2024-09-09 03:51:02 字数 1194 浏览 2 评论 0原文

我使用以下函数来检查查看的帖子是否属于给定 ID 的后代类别。

我如何扩展该函数以检查当前查看的“自定义帖子类型”是否属于给定 ID 的后代类别?

我使用此函数将菜单项设置为“活动”。

功能是:

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

提前致谢!

I use the following function to check whether the viewed post is in a descendant category of the given ID.

How can i extend the function to also check if the current viewed "custom post type" is in a descendant category of the given ID?

I use this function to set a menu item to "active".

The function is:

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

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墟烟 2024-09-16 03:51:02

这不适用于自定义帖子类型吗?你尝试过吗?

Doesn't this work with Custom Post Types? Have you tried?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文