Snippet: Set up OpenGraph meta tags to fix the Facebook Share

Today, Social sharing has become extremely important. Correctly sharing is as important as functioning of the website. If someone share your website on a social site like Facebook and it do not show up properly, that means, you have not developed website properly.

For a WordPress site, implementing it is quite easy. “wp_head” hook does the job. You just need to put the following snippet in your functions.php and update the $site_logo with URL to your logo.

user Facebook’s Debug Tool to referesh the Facebook cache for your link.

Snippet

add_action( 'wp_head', 'og_facebook' );
function og_facebook() {
	global $post;
	$site_logo = get_bloginfo('template_url').'/images/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:title" content="' . get_bloginfo('name') . '" />';
		echo '<meta property="og:image" content="'.$site_logo.'" />';
		echo '<meta property="og:description" content="'.get_bloginfo('description').'" />';
	}
	elseif ( is_singular() ) { // only if a single post or page
		echo '<meta property="og:type" content="article" />';
		echo '<meta property="og:url" content="' . get_permalink() . '" />';
		echo '<meta property="og:title" content="' . get_the_title() . '" />';
		if (has_post_thumbnail( $post->ID )) { // use featured image if there is one
			$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'large' );
			echo '<meta property="og:image" content="' . esc_attr( $image[0] ) . '" />';
		 }else{ // use site logo in case no featured image
			echo '<meta property="og:image" content="'.$site_logo.'" />';
	 	}
		echo '<meta property="og:description" content="'.get_the_excerpt().'" />';

	}
	else{
		echo '<meta property="og:title" content="' . get_the_title() . '" />';
		echo '<meta property="og:image" content="'.$site_logo.'" />';		
	}
}

Result

coming_soon.html page will be displayed when you will visit your website http://www.abc.com. If you want to get in, of course you want, You can browse http://www.abc.com/?test to see your website

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>