X

Facebook Open Graph Snippet to Set Default Image

Snippets by IsItWP

When your website visitors share the posts on social media channels like Facebook, it attaches an image with each post called Facebook open graph. This image can be the featured image of your WordPress post or any other image used in the post. You can also set up a default image for Facebook open graph.

Instructions: Add the following snippet to the functions.php file of your WordPress theme.
You need to set your ADMIN_ID by visiting http://graph.facebook.com/yourfacebookusername, and modify the URL of your site’s logo. Then, you can check that Facebook is getting all the correct information by going to https://developers.facebook.com/tools/debug.

function diww_facebook_image() {
		echo '<meta property="fb:admins" content="ADMIN_ID" />';
		echo '<meta property="og:title" content="' . get_the_title() . '" />';
		echo '<meta property="og:site_name" content="' . get_bloginfo('name') . '" />';

	global $post;
	if ( is_singular() ) { // only if a single post or page
		echo '<meta property="og:type" content="article" />';
		echo '<meta property="og:url" content="' . get_permalink() . '" />';

	if (has_post_thumbnail( $post->ID )) { // use featured image if there is one
		$feat_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
		echo '<meta property="og:image" content="' . esc_attr( $feat_image[0] ) . '" />';
	 }else{ // use site logo in case no featured image
		echo '<meta property="og:image" content="http://yourdomain.com/logo.png" />';
	 }
	}

	if ( is_home() ) { // for homepage only
		echo '<meta property="og:type" content="website" />';
		echo '<meta property="og:url" content="' . get_bloginfo('url') . '" />';
		echo '<meta property="og:image" content="http://yourdomain.com/logo.png" />';
	}
}

add_action( 'wp_head', 'diww_facebook_image' ); 

You may also enjoy creating a Facebook share link.

Comments   Leave a Reply

  1. Astro Gremlin July 6, 2012 at 3:02 pm

    Dave, there was a brief period when I was sharing my posts and Facebook was running an image from my ads, then telling me it was not allowed! This was occurring even when I had a non-ad image at the top of the post. It worked itself out, but this snippet could come in handy to select the desired image.

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!