我的自定义帖子类型(&C);内置Wordpress博客帖子共享内置类别。
我有一段代码,可以循环显示所有(内置)类别,这些类别都有“归档工作”中分配给它们的帖子。php\'
我只想显示分配了CPT(工作)帖子的类别,而不显示任何其他帖子(即可能属于同一类别的任何博客帖子)。然而,我下面的代码显示了所有类别,其中包含来自任何帖子类型的任何帖子,如何修复此问题以仅显示来自工作CPT的类别?
<?php
$args=array(
\'name\' => \'category\',
\'public\' => true,
\'_builtin\' => true
);
$output = \'names\'; // or objects
$operator = \'and\';
$taxonomies=get_taxonomies($args,$output,$operator);
if ($taxonomies) {
foreach ($taxonomies as $taxonomy ) {
$terms = get_terms([
\'post_type\' => array( \'work\' ),
\'taxonomy\' => $taxonomy,
\'hide_empty\' => 1,
]);
foreach ( $terms as $term) {
if ($term->slug == \'all-articles\') {} else {?>
<button class="filter--item" data-filter=".<?php echo $term->slug; ?>"><?php echo $term->name; ?> <span class="checkbox"><i class="i-check"></i></span></button>
<?php } } } } ?>
最合适的回答,由SO网友:Ankita Tanti 整理而成
请尝试以下代码:
$args = array(
\'post_type\' => \'work\',
\'posts_per_page\' => -1,
\'post_status\' => \'publish\'
);
$the_query = new WP_Query( $args );
$my_categories = array();
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$terms = get_the_terms( get_the_ID(), \'category\' );
if ( $terms && ! is_wp_error( $terms ) ) :
foreach ( $terms as $term ) {
if(!in_array($term->term_id, $my_categories))
$my_categories[] = $term->term_id;
}
endif;
}
wp_reset_postdata();
}
if(sizeof($my_categories)) {
foreach ($my_categories as $term_id) {
$category = get_term_by(\'id\', $term_id, \'category\');
if($category->slug!="all-articles") {
?>
<button class="filter--item" data-filter=".<?php echo $category->slug; ?>"><?php echo $category->name; ?> <span class="checkbox"><i class="i-check"></i></span></button>
<?php
}
}
}
希望这对你有帮助!