有什么方法可以从自定义分类法或类别中仅获取父项?
$genres = get_the_term_list($post->ID, 'genres', '<div class="genres"><div class="mta">', '', '</div></div>');
Try this code,
<?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>';
} ?>
You can build the list alone without childrens.
/**
* @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
}
The second option is that you can filter the terms and remove all the terms with parent bigger than 0 for the get_the_term_list()
function.
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 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.