繁体   English   中英

仅获取自定义帖子类型的子条款

[英]Get only child terms of custom post type

我与其他 chld 类别有“徒步旅行”类别。 我只需要获得徒步儿童类别,但我做不到。 这是我的代码(工作正常,只有我必须排除所有其他类别,但这不是一个好的/动态解决方案)。 谢谢!

<ul class="fordesktop">
<?php $customPostTaxonomies = get_object_taxonomies('portfolio');
$category = get_category_by_slug( 'trekking' );
if(count($customPostTaxonomies) > 0)
{
     foreach($customPostTaxonomies as $tax)
     {
         $args = array(
              'orderby' => 'name',
              'show_count' => 0,
              'pad_counts' => 0,
              'hierarchical' => 0,
              'taxonomy' => $tax,
              'title_li' => '',
              'child_of' => $category,
             'exclude' => '10, 19, 20, 21, 22, 26, 29, 30, 31, 35, 36, 37, 41, 42, 43, 44',
             'hide_title_if_empty' => 0
            );

         wp_list_categories( $args );
     }
} ?></ul>

另一种方法是下一个代码,但我不能隐藏空词:

<?php
$term_id = 10;
$taxonomy_name = 'portfolio_category';
$termchildren = get_term_children( $term_id, $taxonomy_name );
 
echo '<ul>';
foreach ( $termchildren as $child ) {
    $term = get_term_by( 'id', $child, $taxonomy_name );
    echo '<li><a href="' . get_term_link( $child, $taxonomy_name ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
?> 

尝试使用get_term_children()

// This will give you an array with the ID's of all child categories of 'trekking':
$cat = get_category_by_slug('trekking');
$cat_id = $cat->term_id;
$child_cat_ids = get_term_children($cat_id, 'category');

如果您更喜欢类别对象列表而不是 ID,另一种方法是:

$cat = get_category_by_slug('trekking');
$cat_id = $cat->term_id;
$child_cats = get_categories(['parent' => $cat_id]);

See more info here: https://developer.wordpress.org/reference/functions/get_term_children/ https://developer.wordpress.org/reference/functions/get_categories/

编辑:

如果你想在你的代码中使用wp_list_categories() ,试试这个:

$cat = get_category_by_slug('trekking');
$cat_id = $cat->term_id;
$args = array(
        'child_of'   => $cat_id,
);
wp_list_categories($args);

编辑2:

调整了自定义分类的解决方案:

$tax = get_term_by('slug', 'trekking', 'portfolio');
$tax_id = $tax->term_id;
$args = array(
'child_of'   => $tax_id,
'taxonomy' => 'portfolio',
'orderby' => 'name',
'show_count' => 0,
'pad_counts' => 0,
'hierarchical' => 0,     
'title_li' => '',
'hide_title_if_empty' => 0
);
wp_list_categories($args);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM