如何在WordPress中仅显示自定义文章类型newsroom关联的分类法类型
解决方法
要只显示自定义文章类型「newsroom」关联的「types」分类术语,你需要修改get_terms的参数,限定仅返回与newsroom文章绑定的分类项,具体修改如下:
修改后的完整代码
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter"> <input type="hidden" name="action" value="resource_filter"> <?php // 获取所有newsroom类型文章的ID数组 $newsroom_post_ids = get_posts(array( 'post_type' => 'newsroom', 'posts_per_page' => -1, 'fields' => 'ids' // 仅获取ID字段,提升性能 )); // 仅获取与newsroom文章关联的types分类术语 if( $terms = get_terms( array( 'taxonomy' => 'types', 'orderby' => 'name', 'object_ids' => $newsroom_post_ids, // 限定关联的文章范围 'hide_empty' => false // 若需隐藏无关联文章的术语,可改为true ) ) ) { ?> <div class="types-filter"><h3>Types</h3> <?php foreach ( $terms as $term ){ ?> <label class="MuiFormControlLabel-root"> <span class="MuiButtonBase-root MuiIconButton-root jss317 MuiCheckbox-root MuiCheckbox-colorSecondary MuiIconButton-colorSecondary" aria-disabled="false"> <span class="MuiIconButton-label"> <input type="checkbox" name="types_filter[]" id="checkbox_types_filter_<?php echo $term->term_id; ?>" class="resource-filter-checkbox" value="<?php echo $term->term_id; ?>" data-indeterminate="false" data_term_name="<?php echo $term->name; ?>"> </span> </span> <span class="MuiTypography-root MuiFormControlLabel-label MuiTypography-body1"> <p class="MuiTypography-root MuiTypography-body2"><?php echo $term->name; ?></p> </span> </label> <?php } ?> </div> <?php } ?> </form>
关键修改说明
- 先通过
get_posts获取所有newsroom类型文章的ID,仅提取ID字段减少资源消耗 - 在
get_terms参数中添加object_ids,传入上述ID数组,让分类术语仅筛选与这些文章关联的项 hide_empty参数可按需调整:设为true会隐藏当前无关联newsroom文章的术语,设为false则保留所有曾关联过的术语
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

