Hello Dear Stack Overflow friends! I’ve been trying to solve this problem for a couple of days with no success. I’ve read almost every post available here at Stack Overflow but I can’t find out how to solve this.
When I share a link on Facebook, the thumbnail corresponds to the image I defined in the
meta property=”og:image”
It works and everything is fine there… But,
I would like that each post could display its own featured image as a thumbnail when shared. How on earth can I do that?
I’ve tried with this code in function.php
function insert_image_src_rel_in_head() {
global $post;
if ( !is_singular()) //if it is not a post or a page
return;
if(!has_post_thumbnail( $post->ID )) { //the post does not have featured image, use a default image
$default_image="http://example.com/image.jpg"; //replace this with a default image on your server or an image in your media library
echo '<meta property="og:image" content="' . $default_image . '"/>';
}
else{
$thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' );
echo '<meta property="og:image" content="' . esc_attr( $thumbnail_src[0] ) . '"/>';
}
echo "
";
} add_action( 'wp_head', 'insert_image_src_rel_in_head', 5 );
And nothing happens…
I’ve also tried this code in header.php
<?php
global $wp_query;
$thePostID = $wp_query->post->ID;
if( has_post_thumbnail( $thePostID )){
$thumb_id = get_post_thumbnail_id( $thePostID );
$image = wp_get_attachment_image_src( $thumb_id );
echo '<meta property="og:image" content="'.$image[0].'" />';
} ?>
No success there either.
The featured image is activated in the functions.php like this.
add_theme_support('post-thumbnails');
As I said, all og tags are set.
What Is happening? It’s not a cache thing because I’m using the facebook debugger to flush it.
I will be eternally grateful if anybody out there can help me.
Thanks a lot.
Benjamin.
I think you should try like
also, pls check your source code after updating this if
<meta property
is displaying correct when site is renderedOk I fixed this… Maybe this will help other users with the same problem… The reason it was using the same thumbnail in every link despite rendering the correct image in the source code is because of the
<meta property="og:url" content="
line.I entered there the URL of the site and of course, the canonical URL ruled them all, and the debugger went there to fetch the featured image. I replaced that value with
And that did it. Thank you for your kind help I hope this question helps others solve similar issues.
You can use meta property like this.