使用array_slice 并获取数组的前5个元素:
<?php
$term_id =182;
$taxonomy_name = \'geram_category\';
$term_children = get_term_children( $term_id, $taxonomy_name );
$term_children = array_slice( $term_children, 0, 5, true );
foreach ( $term_children as $child ) {
$term = get_term_by( \'id\', $child, $taxonomy_name);
echo \'<li><a href="\' . get_term_link( $child, $taxonomy_name ) . \'">\' . $term->name . \'</a></li>\';
}
?>
如果只想获取前5个子术语中的帖子,可以通过对每个术语使用WP\\u查询来筛选数组,以检查该术语是否有帖子:
<?php
$term_id =182;
$taxonomy_name = \'geram_category\';
$term_children = get_term_children( $term_id, $taxonomy_name );
$term_children = array_filter( $term_children, function( $term_id ) {
$args = array(
\'post_type\' => \'spanish\',
\'posts_per_page\' => 1,
\'tax_query\' => array(
array(
\'taxonomy\' => \'geram_category\',
\'field\' => \'term_id\',
\'terms\' => $term_id,
),
),
);
$query = new WP_Query( $args );
if( $query->found_posts ) {
return true;
} else {
return false;
}
});
$term_children = array_slice( $term_children, 0, 5, true );
foreach ( $term_children as $child ) {
$term = get_term_by( \'id\', $child, $taxonomy_name);
echo \'<li><a href="\' . get_term_link( $child, $taxonomy_name ) . \'">\' . $term->name . \'</a></li>\';
}
?>