No post image when pasting link into Facebook

This thread’s solution proposes to add an absolute link to the post image within head tags so that, when pasting post URL into Facebook, the post image appears on Facebook.

However this is laborious because in WordPress, getting the post image within head tags requires to execute loop code in there, and that doesn’t sound particularly elegant to me. Perhaps there is some smarter solution out there?

Solutions Collecting From Web of "No post image when pasting link into Facebook"

It’s assumed that your images are Facebook Image Sharing Compliant in size and quality, and you are trying to share single posttype ‘post’ only from a single template (single.php), and you are storing your image as post thumbnail.

The following code will grab the post thumbnail (size = large) of particular post and put that in the og:image meta tag on the <head> using wp_head() on header file.

<?php
function enqueue_open_graph_metadata() {
    if( is_single() ) {
        global $post;
        $image_url = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' ); //thumbnail, medium, large, full
        echo '<meta property="og:image" content="'. esc_url( $image_url ) .'" />'. "\n";            
    }
}
add_action( 'wp_head', 'enqueue_open_graph_metadata' );

There are plenty of plugins out there doing the same things for you, for other social sites, like Twitter, GooglePlus etc. My personal favorite is Yoast’s WordPress SEO. But there are many in this sort of.