Show current page featured image in sidebar

How do I call the current post’s featured image in the sidebar? and if there is none, then a backup image?

Solutions Collecting From Web of "Show current page featured image in sidebar"

I’m assuming you’re going to be outputting this on a singular page (Post, Page, Attachment)?

If so, the easiest thing to do is to put your post AND sidebar content inside the Loop, so that you have access to the $post global, and post-related template tags.

Alternately, you could define a variable, inside the Loop, to hold $post-ID so that you can reference it outside of the Loop, i.e. in your sidebar.

In either case, inside the Loop, you would have e.g.:

$post_id = get_the_ID();

Then, in your sidebar:

if ( has_post_thumbnail( $post_id ) ) {
    the_post_thumbnail( 'sidebar_post_thumbnail' );
} else {
    // code to output your default image

Note: I’m assuming you’ll create a custom image size to output in the sidebar, e.g.

add_image_size( 'sidebar_post_thumbnail', 150, 9999, false );

(which goes in functions.php, of course)