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 ); the_post_thumbnail(''); endforeach; wp_reset_query();
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.
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.
Where are you getting
$page_idfrom? It might be worth echoing that out onto the page as well.
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 ) the_post_thumbnail(); wp_reset_query();
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?!
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.
- The topic ‘Why is Featured Image Repeating Five Times’ is closed to new replies.