0

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?

2

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.

  • 1
    get_the_post_thumbnail() doesn't return the thumbnail URL, it returns a <img> element. You need to use other functions, like wp_get_attachment_image_src(), to get the URL of the thumbnail. – cybmeta Sep 8 '15 at 14:04
  • @cybmeta thanks a lot. I copied the code from somewhere else, and just mistakenly from other line. :( Thanks for figuring that out. Fixed now. – Mayeenul Islam Sep 8 '15 at 16:41
  • @drake035 make sure, your images are Facebook Image Sharing Compliant – Mayeenul Islam Sep 9 '15 at 6:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.