I am using the following code to display the related posts but it is showing posts for that category only like brand showing brand posts only. What I am looking for is if I select any of the posts under child (brand, advertising, online etc), it should display all posts under marketing so I will not have to assign multiple categories to the posts

  • Subject
    • Marketing(3)
      • Brand(1)
      • Advertising(1)
      • Online(1)
<?php

$related = get_posts( array( 'category__in' => wp_get_post_categories($post->ID), 'numberposts' => 5, 'post__not_in' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
<ul> 
    <li>
    <a href="https://wordpress.stackexchange.com/questions/257775/<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
        <?php the_content('Read the rest of this entry &raquo;'); ?>
    </li>
</ul>   

<?php } wp_reset_postdata(); ?>

1 Answer
1

Just change this one line:

   $cat_obj = $wp_query->get_queried_object();
    $thiscat_id = $cat_obj->term_id;
    $thiscat = get_category($thiscat_id);
    $chi = array();
    if (!empty($thiscat->parent)) {
        $parentcat = get_category($thiscat->parent);
        $categories_chi=get_categories(
            array( 'parent' => $parentcat->cat_ID )
        );

        foreach ($categories_chi as $key => $value) {
            $chi[] = $value->cat_ID;
        }
        $pare = array($parentcat->term_id);
        $ids = array_merge($pare, $chi);
    } else {
        $ids = array($cat_obj->term_id);
    }

    $related  = get_posts(array( 'category__in' => $ids, 'numberposts' => 10));

Leave a Reply

Your email address will not be published. Required fields are marked *