Display Related Posts in Blog

I want to display the list of related posts at the end of my blog post. I would like the main image to display if possible, but I can't seem to get this to work right. Any help would be a appreciated.

Comments

  • edited April 2016
    You should be able to loop through the related posts like so:
    foreach($post->related_posts as $related) : echo $related->main_image; endforeach;
  • edited April 2016
    Thank you for replying. And that piece of code helped me load one related post, but it's not displaying all the related posts.

    I also removed "endforeach;" because it caused an error.

    Here's what I have:

    php foreach($post->related_posts as $related)
    php if (!empty($related)) :
    php echo $related->thumbnail_image

    php endif;
  • edited 4:25PM
    The code above was missing the ending semicolon after:
    echo $related->main_image;
  • edited 4:25PM
    The semi colon is there in my version, I must have missed it when I cut and pasted.

    It still isn't showing all the images. It's only showing 1 image.
  • edited 4:25PM
    Just to confirm, each post has a main_image value associated with it? What is showing instead?
  • edited April 2016
    I have a thumbnail image in the database as well as a main image. They are different images.

    I tried the suggested:

    echo $related->main_image;

    but it gave me the same results with the main image. It only displays one.
  • edited 4:25PM
    So when you execute that foreach loop above, does it loop through all the related posts for the selected post and output the main_image for each related post or does it output something different and if so what does it output for each related post main_image value?
  • edited 4:25PM
    It only outputs one of the related posts, and returns the image for it.
  • edited 4:25PM
    How many posts are associated with it under the Associations tab?
  • edited 4:25PM
    One of the posts has 2, another has 4. Only one related post for each is showing.
  • edited 4:25PM
    Hmm...I'm not able to replicate this issue. I tested it with the following and it behaved as expected:
    $related = $post->related_posts; foreach($post->related_posts as $p) : echo '<img src="'.$p->thumbnail_image.'"><br>'; endforeach;
  • edited 4:25PM
    Awesome! That worked for me.

    Where it echo's the image src I had to include a path to the folder for the images to load.

    echo '<img src="/assets/images/blog'.$p->thumbnail_image.'"><br>';


    Thank you.
Sign In or Register to comment.