1
votes

I work in my Single.php template for Wordpress theme, but in related posts I have problem!

I want show related posts from parent category child for example I add parent category with A name in Wordpress, in this parent category we have B,C,D and other child categories that can set for every post in Wordpress posts area.

Well I publish new post in D (or other A children) category I want show in related posts box, other from D (or other A children) category.

this is my work but not good

$related = get_posts( array(
'category__in' => wp_get_post_categories( $post->ID ),
'numberposts'  => 3,
'post__not_in' => array( $post->ID )
) );

I'm newbie please help me, thanks.

1
So on D you want to show related posts that are in one of these catagories A->B A->C and A->D right?Nico Shultz
No if I select D show other from D if I select B show other from B like this, I have other parent like A but I want show related item just from A related child .ThisIsWilliam

1 Answers

0
votes

This code wil get a taximony with a parent so in your case it wil get the child but if you can have a post that is A->B AND A->C it wil only get related posts from the first catagory selected eg(A->B)

$terms = wp_get_post_terms($post->ID, 'category');
if (count($terms)) {
    foreach ($terms as $term) {
        if ($term->parent != 0) {
            $relatedTerm = $term;
            break;
        }
    }
    $related = get_posts(array(
        'category__in' => $relatedTerm->term_id,
        'numberposts'  => 3,
        'post__not_in' => array($post->ID),
    ));
}