integrating facebook share or like with open graphics og tags on wordpress

There are a million different ways of adding a facebook share or like button to your wordpress site, there are plugins, there are tutorials, but those never works right.

What is the proper way of adding Facebook like button ?

More often that not, when you add the Facebook like button to your Wordpress website, the like button picks up the wrong content, the wrong image, and the wrong description and wrong link if you set it to work automatically, if you're a Wordpress developer who frequently uses premium themes like I do, there may be thumbnail images attached with the posts (sometimes you want the like button to display the first post in the page, in the home page, may be you want to display your logo) 

And if you've done enough research, you'd know that you should use the Open Graph Protocol og:tags, but og:tags works only in the header, may be the image you want to put up could be the generated within the loop, so how do you put an image that's in the loop ? Its simple, you create mulitple loops. Create a loop in the header (between the  tags) that will generate content for the meta data and then generate another one for your posts. Here's how I did it, if you're too lazy, you could copy my code.

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/" <?php language_attributes(); ?>>
<?php if (have_posts()):while(have_posts()):the_post();endwhile;endif;?>
<!-- Facebook Opengraph -->
<meta property="fb:app_id" content="your_app_id" />
<meta property="fb:admins" content="your_admin_id" />
<meta property="og:url" content="<?php the_permalink() ?>"/>
<?php if (is_single()) { ?>
<meta property="og:title" content="<?php single_post_title(''); ?>" />
<meta property="og:description" content="<?php echo strip_tags(get_the_excerpt($post->ID)); ?>" />
<meta property="og:type" content="article" />
<meta property="og:image" content="<?php echo wp_get_attachment_thumb_url( get_post_thumbnail_id( $post->ID ) ) ?>" />
<?php } else { ?>
<meta property="og:site_name" content="<?php bloginfo('name'); ?>" />
<meta property="og:description" content="<?php bloginfo('description'); ?>" />
<meta property="og:type" content="website" />
<meta property="og:image" content="<?php bloginfo('template_url') ?>/path/to-your/logo.jpg" />
<?php } ?>

1 comment: