Related posts by current posts child category

I'm trying to use this code to display related posts by the same category as the current post but if the post is in a child category, i need to show related posts by that child category, not the parent unless there's no more posts in the same child category.

$categories = get_the_category( get_the_ID() );

$args = array (
    'child_of' = $categories[0], 
    'title_li' = ''
);

$terms = wp_get_post_terms( get_the_ID(), 'category', $args ); 

$terms_ids = [];

foreach ( $terms as $term ) {
    $terms_ids[] = $term-term_id;
}

$args = array(
    'post_type'      = 'posts',
    'posts_per_page' = 8,
    'orderby'        = 'rand', 
    'post__not_in'   = array( get_queried_object_id() ),
    'tax_query'    = array(
    'relation'     = 'AND',
array(
    'taxonomy' = 'brand',
    'field'    = 'term_id',
    'terms'    = $terms_ids,
     ),),  
);
        
$loop = new WP_Query( $args );

I'm not sure if i also need to include the tax_query.

Topic wp-query categories Wordpress

Category Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.