I’m trying to show a post thumbnail outside of the loop. The reason for this is that i want the featured image to show inside a custom page template, which will set the header image for the particular page for which the custom page template is set.
I’ve tried the obvious the_post_thumbnail();
and as expected, it didn’t work. What’s the best solution for using the featured image outside of the loop?
The custom page template code i’m working with…
<div id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<div class="home-header-image">
<?php IMAGE WILL GO HERE ?>
</div>
<div class="top_items_container">
<?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Home Top Content')) :
endif; ?>
</div><!-- .top_items_container -->
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-links"><span class="page-links-title">' . __( 'Pages:', 'twentythirteen' ) . '</span>', 'after' => '</div>', 'link_before' => '<span>', 'link_after' => '</span>' ) ); ?>
</div><!-- .entry-content -->
<footer class="entry-meta">
<?php edit_post_link( __( 'Edit', 'twentythirteen' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- .entry-meta -->
</article><!-- #post -->
<?php comments_template(); ?>
</div><!-- #content -->
</div><!-- #primary -->
Take a look into the function single_post_title() in the general-template.php file and you will find following:
and in that function you also see:
which gives you the title of the page outside of the loop.
Now to get the Featured Image you simply do the following
As you can read in the source of
get_the_post_thumbnail()
, per default it relies onget_the_ID()
if no ID/1st-argument was provided. Andget_the_ID()
relies onget_post()
which relies on the global$post
object filled bysetup_postdata()
which gets filled by global$wp_query
/the currentWP_Query
object.So the obvious thing to do is simply provide the
ID
of the post that is the main post for this attachment. In other words the first post this attachment got assigned to. Not very convenient, I know.There’s another public API function that allows fetching the attachment by its ID directly:
Now this will return the HTML for the attachment. If you just want the plain data, go with
wp_get_attachment_image_src()
which returns an array (url, width, height), or false, if no image is available.
To get the src only, do the following:
get_the_post_thumbnail()
will accept a post ID as the first parameter. From the Codex:Without seeing more context I don’t think I can do better than that broad outline and generic example.
If your thumbnail is attached to the page assigned to this template, then the following should do it:
$post
will be the current post object and it is set before the Loop begins to the first post in the Loop. On a single page there is only one post so$post
should be one you want.