虽然@sri answer 帮助,这里有一个函数,即使深度大于2,也可以获得最深的类别。(摘自并修改自this answer.). 此函数使用wordpress的函数get_ancestors().
function get_deepest_term($post_id){
$the_terms = get_the_terms( $post_id, \'Category\' );
if ( $the_terms && ! is_wp_error( $the_terms ) ) {
$deepest = $the_terms[0];
$depth = 0;
$term_depth= 0;
// Find the deepest term
foreach( $the_terms as $term ) {
$term_ancestors = get_ancestors( $term->term_id, \'Category\' );
if ( $term_ancestors ) {
$term_depth = count( $term_ancestors );
}
else $term_depth= 0;
if ( $term_depth > $depth ) {
$depth = $term_depth;
$deepest = $term;
}
} // END: foreach( $the_terms as $term )
} // END: if ( $the_terms && ! is_wp_error( $the_terms ) )
return $deepest;
} // END: function get_deepest_term($post_id)
然后,可以使用上述函数循环遍历最深类别的帖子,如下所示(代码取自
@sri answer):
<?php
//Usual args parameter & WP_Query loop
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'posts_per_page\' => 5,
\'orderby\' => \'rand\',
\'post__in\' => array(get_deepest_term( get_the_ID() )->term_id)
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) { ?>
<ul>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li>
<?php endwhile;
wp_reset_post_data();
} // END: if( $my_query->have_posts() ) ?>
</ul>
所以,我的问题是,有没有一种方法可以让我获得当前帖子最低级别子类别的ID,但忽略它的父类别?
$lowest_tier_child_category = get_deepest_term( get_the_ID() )->term_id