繁体   English   中英

有什么方法可以从自定义分类法或类别中仅获取父项?

[英]Is there any way to get only parent terms from custom taxonomy or category?

有什么方法可以从自定义分类法或类别中仅获取父项?

 $genres = get_the_term_list($post->ID, 'genres', '<div class="genres"><div class="mta">', '', '</div></div>');

试试这个代码,

 <?php $terms = get_terms( array( 
        'taxonomy' => 'taxonomy_name',
        'parent'   => 0
    ) );
    if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
        echo '<ul>';
        foreach ( $terms as $term ) {
            echo '<li>' . $term->name . '</li>';
        }
        echo '</ul>';
    } ?>

您可以单独建立列表,而无需孩子。

/**
 * @param post_id can use 'get_the_ID()'
 * @param taxonomy for example 'category'
 */
$terms = wp_get_object_terms($post_id, $taxonomy, array('parent'=>'0'));
foreach($terms as $term) {
    ?>
    <a href="<?php echo get_term_link($term->term_id); ?>"><?php echo $term->name; ?></a> 
    <?php
}

第二种选择是,您可以对get_the_term_list()函数过滤条件并删除其父项大于0的所有条件。

function remove_child_terms($terms, $post_id, $taxonomy) {
    /**
     * Add some condition here to limit this for your custom taxonomy
     * if($taxonomy == 'something') {
     */
    foreach($terms as $key => $term) {
        if($term->parent !== 0) {
            unset($terms[$key]);
        }
    }
    /**
     * }
     */
    return $terms;
}
add_filter( 'get_the_terms', 'remove_child_terms', 10, 3 );

暂无
暂无

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

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