如果您想根据您提供的单个类别显示子类别和相关帖子的列表,您可以使用以下代码。确保使用您自己的分类名称、post_type 和术语:
function ow_subcategories_with_posts_by_category( $taxonomy, $post_type, $term ) {
$category = get_term_by( 'slug', $term, $taxonomy );
$cat_id = $category->term_id;
// Get all subcategories related to the provided $category ($term)
$subcategories = get_terms(
array(
'taxonomy' => $taxonomy,
'parent' => $cat_id,
'orderby' => 'term_id',
'hide_empty' => true
)
);
?>
<div>
<?php
// Iterate through all subcategories to display each individual subcategory
foreach ( $subcategories as $subcategory ) {
$subcat_name = $subcategory->name;
$subcat_id = $subcategory->term_id;
$subcat_slug = $subcategory->slug;
// Display the name of each individual subcategory with ID and Slug
echo '<h4>Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug . '</h4>';
// Get all posts that belong to this specific subcategory
$posts = new WP_Query(
array(
'post_type' => $post_type,
'posts_per_page' => -1, // <-- Show all posts
'hide_empty' => true,
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'terms' => $subcat_id,
'field' => 'id'
)
)
)
);
// If there are posts available within this subcategory
if ( $posts->have_posts() ):
?>
<ul>
<?php
while ( $posts->have_posts() ): $posts->the_post();
//Show the title of each post with the Post ID
?>
<li>Post: <?php the_title(); ?> - ID: <?php the_ID(); ?></li>
<?php
endwhile;
?>
</ul>
<?php
else:
echo 'No posts found';
endif;
wp_reset_query();
}
?>
</div>
<?php
}
ow_subcategories_with_posts_by_category( 'name-of-your-taxonomy', 'name-of-your-post-type', 'name-of-your-specific-term' );
'name-of-your-taxonomy' 是主要分类的名称。例如:'victual_category'
'name-of-your-post-type' 是您的帖子类型的名称。例如:'victual'
'name-of-your-specific-term' 是您要使用的特定类别的名称,以便可以显示属于该类别的子类别。例如:“食物”
所以如果我调用函数:
ow_subcategories_with_posts_by_category( 'victual_category', 'victual', 'food' );
这将显示所有子类别及其各自属于食品类别分类法的帖子:
子类别:开胃菜 - ID:35 - 蛞蝓:开胃菜
- 帖子:薯条和莎莎酱 - ID:464
- 帖子:Queso - ID:465
子类别:炸玉米饼 - ID:36 - 蛞蝓:炸玉米饼
- 职位:Al Pastor - ID:466
- 职位:Fish Al Pastor - ID:467