如果要显示自定义分类法的所有类别和子类别,请使用此代码并确保提供分类法的slug。
function ow_categories_with_subcategories( $taxonomy ) {
// Get the top categories that belong to the provided taxonomy (the ones without parent)
$categories = get_terms(
array(
\'taxonomy\' => $taxonomy,
\'parent\' => 0, // <-- No Parent
\'orderby\' => \'term_id\',
\'hide_empty\' => true // <!-- change to false to also display empty ones
)
);
?>
<div>
<?php
// Iterate through all categories to display each individual category
foreach ( $categories as $category ) {
$cat_name = $category->name;
$cat_id = $category->term_id;
$cat_slug = $category->slug;
// Display the name of each individual category
echo \'<h3>Category: \' . $cat_name . \' - ID: \' . $cat_id . \' - Slug: \' . $cat_slug . \'</h3>\';
// Get all the subcategories that belong to the current category
$subcategories = get_terms(
array(
\'taxonomy\' => $taxonomy,
\'parent\' => $cat_id, // <-- The parent is the current category
\'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>\';
}
?>
</div>
<?php
}
?>
</div>
<?php
}
ow_categories_with_subcategories( \'the_name_of_your_taxonomy\' );