How to show parent category’s posts in child’s category’s post of custom post type

Question

I am working on related posts of custom post type. I have created a separate template file (single-mylisting.php) My current scenario is to show related post of custom post type which is working fine. I want to show parents category’s post if child has no post. Right now if child category has no post it shows nothing instead of showing nothing i want to show posts from parent category. I am using the following code.

<?php

//get the taxonomy terms of custom post type
$customTaxonomyTerms = wp_get_object_terms( $post->ID, 'your_taxonomy', array('fields' => 'ids') );

//query arguments
$args = array(
    'post_type' => 'your_custom_post_type',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    'orderby' => 'rand',
    'tax_query' => array(
        array(
            'taxonomy' => 'your_custom_taxonomy',
            'field' => 'id',
            'terms' => $customTaxonomyTerms
        )
    ),
    'post__not_in' => array ($post->ID),
);

//the query
$relatedPosts = new WP_Query( $args );

//loop through query
if($relatedPosts->have_posts()){
    echo '<ul>';
    while($relatedPosts->have_posts()){ 
        $relatedPosts->the_post();
?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php
    }
    echo '</ul>';
}else{
    //no posts found
}

//restore original post data
wp_reset_postdata();

?>
0
, Harvey 1 year 2020-07-27T07:19:21-05:00 0 Answers 38 views 0

Leave an answer

Browse
Browse