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.