wp query – How would you list ids for each post in a child category rather than each child cat

Question

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.

0
Dev 3 months 2022-05-21T03:42:30-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse