wordpress - 获取 CPT 的父类别
问题描述
我正在处理一个索引页面,其中列出了自定义帖子类型的所有帖子。我一直在使用<?php echo strip_tags(get_the_term_list( $post->ID, 'genre', ' ',' • ')); ?>
.
我们需要添加子类别,但我不希望这些显示在索引页面上 - 只是父类别。已尝试使用get_term_parents_list
此处的其他一些示例,但无法正常工作。
任何人都可以帮忙吗?
解决方案
您可以使用get_the_terms
过滤器更改要返回的条款。
add_filter('get_the_terms', 'only_parent_genre', 10, 3);
function only_parent_genre($terms, $post_id, $taxonomy) {
// TODO for you : Add condition to heck if you are not on your custom index too.
if(is_admin() || $taxonomy !== 'genre') {
return $terms;
}
// Loop over terms and if parent is something different than 0, it means that's its a child term
foreach($terms as $key => $term) {
if($term->parent !== 0) {
unset($terms[$key]);
}
}
return $terms;
}
推荐阅读
- javascript - firebase currentUser 在页面重新加载时为空
- c# - SonarQube 错误的错误?使用 Null Coalesce 和字符串赋值
- python - 如何为 celery 任务日志指定文件路径?
- reactjs - 反应笑话快照测试 - 更改目录结构
- vb.net - 如果语句为真,则 End If 不会立即继续
- python - 在 Scrapy 中使用分页访问多个页面
- pandas - Should I use classes for pandas.DataFrame?
- python - 在同一个 .py 文件上与另一个人进行实时协作?
- node.js - 如何使用 mongoose 和 Node.js 请求新创建的模型?
- javascript - 如何在新行上粘贴复制的链接?