0

At the bottom of each post, I want to display posts that have the same tag. Based on numerous examples of function doing something similar, I created the function below. I call it from with in the loop from the custom post php that I created. It's called succesfully, but I don't get the list of titles that I expect to get. How do I solve this?

function show_related(){

    $posttags = get_the_tags();
    if ($posttags) {
        $ids = array();
        $relatedpostids = array();
        foreach ($posttags as $tag){
            $id =  $tag -> term_id ;
            $ids[] = $id;
        }
        foreach ($ids as $id){
             $args = array(
                'tag_id' => $id,
            );
            $posts_array = get_posts( $args );
            foreach( $posts_array as $post ) {
                echo the_title();
            }
        }

    }
}

1 Answer 1

1
foreach( $posts_array as $post ) {
        echo the_title();
}

I think the problem is you call the_title() without setup_postdata first

If I were you, I'll simply use $post->post_title.

foreach( $posts_array as $post ) {
        echo $post->post_title;
}

This is because you are "get_posts"ing within a loop, and setup_postdata will change global variable $post which is set with the current post's information while The Loop is running.

2
  • Thanks @Jesse, but I don't understand it completely. I tried foreach( $posts_array as $post ) { setup_postdata( $post ); echo the_title($post->post_title); } But still no luck.
    – kslstn
    Commented Feb 28, 2013 at 8:23
  • foreach( $posts_array as $post ) { echo $post->post_title; }
    – Jesse
    Commented Feb 28, 2013 at 9:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.