WordPress 自定义分类法 - 如果不是父术语

标签 wordpress custom-post-type custom-taxonomy

我有一个包含两个级别术语的自定义分类法。

  • 父术语
    • 子项
    • 子项
  • 父术语
    • 子项
    • 子项
  • 父项(无子项)

我使用的是自定义 archive.php 模板,其中包含一些 HTML,我只想在没有子术语的术语上显示该 HTML。

这是我尝试过的...

$taxonomy = 'custom_tax';
$term = get_queried_object();

$children = get_terms( $term->taxonomy, array( 'parent' => $term->term_id ) );

if(!$children) {
    echo '<p>HTML only terms without child terms</p>';
}

如果它是子术语,但不适用于没有子术语的父术语,则此方法有效!

请问有什么帮助吗?

最佳答案

get_terms 参数中将 parent 设置为 0,将仅返回顶级分类术语:

$terms = get_terms( array( 
    'taxonomy' => 'custom_tax',
    'parent'   => 0
) );

然后您可以根据是否存在子术语来过滤这些结果。此 get_term_children 函数将返回子术语数组:

$term_children = get_term_children( $term_id, $taxonomy_name );

关于WordPress 自定义分类法 - 如果不是父术语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58507739/

相关文章:

php - 在 Wordpress 中加载表行的更多按钮

php - 通过标签收集自定义帖子类型

php - 删除自定义帖子类型的 URL 结构

php - 如何在循环内显示自定义帖子的选定自定义分类法而无需链接和回显?

批量删除垃圾邮件 Wordpress 用户的 MySQL 查询

php - 为什么无法访问我的网站(在 Wordpress 中)?

wordpress - 新的 Wp_Query() 或 pre_get_posts() 来查看自定义帖子类型的所有帖子?

php - 在 Woocommerce 3.3 中为产品短代码使用自定义分类

php - 获取 Woocommerce 文件中当前产品类别的子类别

php - WordPress/WooCommerce : cronjob not firing function within class that extends WC_Email