Although @sri answer helps, here is a function that will get the deepest category even if depth is greater than 2. (Taken and modified from this answer.). This function uses wordpress's function 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)
Then the above function can be used to loop through posts from deepest category as follows (Code taken and adjusted from @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>
So, my question is, is there a way that I can get the ID of the current post's lowest tier child category, but ignore it's parent(s)?
$lowest_tier_child_category = get_deepest_term( get_the_ID() )->term_id