WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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();

share|improve this question
up vote 1 down vote accepted
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.

share|improve this answer
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 Feb 28 '13 at 8:23
foreach( $posts_array as $post ) { echo $post->post_title; } – Jesse Feb 28 '13 at 9:05

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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