The Support Forums will be in read-only mode for a scheduled maintenance window on 01 September 2016 14:00 UTC - 20:00 UTC. More information.

[resolved] Why is Featured Image Repeating Five Times (7 posts)

  1. Hi there,

    I am trying to call in a page's featured image outside the loop.

    This is the code I'm using in the sidebar:

    $my_page = get_posts("p=$page_id");
    	if( $my_page )
    	foreach( $my_page as $my_post ) : setup_postdata( $my_post );

    It had been working fine earlier but for some reason now the featured image is repeating five times on the page, one underneath the other. Any clues as to why would be appreciated. I've tried turning off everything else in the sidebar thinking something else (widget or whatnot) might be conflicting, to no avail.

    The code was found here: http://wordpress.org/support/topic/display-featured-image-on-indexphp-outside-the-loop

    Thanks for any suggestions.

  2. If you echo the_title() instead, does that ALSO spit it back 5 times?

    I'd be persinkity to have it echo $my_post at the beginning to see what the various values are actually set as.

  3. esmi
    Forum Moderator
    Posted 5 years ago #

    Where are you getting $page_id from? It might be worth echoing that out onto the page as well.

  4. Hi there - thanks for the suggestions. Someone on Twitter just suggested that the foreach loop could be causing the repeat. I commented out the opening and closing foreach lines and that seems to have fixed the problem!

    Code now looks like this:

    $my_page = get_posts("p=$page_id");
    if( $my_page )
  5. OK, here's something weird. Apparently it works with just


    Esmi - you asked "Where are you getting $page_id from?" - well that was a good question. Apparently it was from part of the sample code I was not actually using, so I commented everything out except the_post_thumbnail() and lo and behold, it works.

    I guess this means it works outside the loop by default?!

  6. esmi
    Forum Moderator
    Posted 5 years ago #

    It will be pulling the post-thumb from the current page via $post. If you look at get_the_post_thumbnail in wp-includes/post-thumbnail-template.php, you'll see the first line of the function checks to see if there if a post_id has been passed. If it hasn't, it sets it to the current post id.

  7. Thanks for pointing me to that. I need more PHP schooling so I can read and understand this code better...

Topic Closed

This topic has been closed to new replies.

About this Topic


No tags yet.