Add a Facebook Like Button to Your WordPress Site

Posted on

By Michael Fields

Facebook. Basically, if you use the internet, you’ve heard of it. In this brief tutorial, I will show you a rather easy way to integrate your WordPress powered website with one of the most popular social networking sites on the web today.

In the time that has elapsed since I wrote this tutorial I have coded a much better solution for enabling WordPress to create open graph meta tags. The code can be found on Github.

Facebook Setup

The first thing that you will need to do is register your site with Facebook. This is done by creating a new application. After you fill out the form, Facebook will provide you with an App ID and an App Secret – two rather long numbers used to identify your website. I suggest that you copy all information on this page and paste it somewhere safe for future reference. We will be using the App ID in our code.

HTML Meta Tags

Setting up a few meta tags in the head of your html document allows you to fine tune how your pages and posts will be displayed in Facebook. There are three different meta tags that you can add:

  • Title: This should be set to the title of your post or page. The example below will pull this data from the global $post array.
  • Site Name: The name of your website. Perhaps the most easiest thing to do here is set meta tag to use the value returned by WordPress core function get_bloginfo().
  • Image: The image that will be used to create the thumbnail when your page is shared on someone’s Facebook Wall. In the example below, I have chosen to use the WordPress Post Thumbnail which is now known as the Featured Image in WordPress 3.0. If no Featured Image has been set, this meta tag will not be printed.
function mfields_facebook_meta() {
    if ( is_singular() ) {
        $image = '';
        if ( has_post_thumbnail( get_the_ID() ) ) {
            $image = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
        }
        print "\n" . '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '"/>';
        print "\n" . '<meta property="og:site_name" content="' . esc_attr( get_bloginfo() ) . '"/>';
        if ( ! empty( $image ) ) {
            print "\n" . '<meta property="og:image" content="' . esc_url( $image ) . '"/>';
        }
    }
}
add_action( 'wp_head', 'mfields_facebook_meta' );

The Like Button

The following code will add the actual Like button to the end of your content.

add_filter( 'the_content', 'mfields_facebook_like_link' );
function mfields_facebook_like_link( $c ) {
	return $c . "\n\t" . '<p><fb:like href="' . get_permalink() . '"></fb:like></p>';
}

Facebook SDK

The third and final step is to add the Facebook SDK to your page. You will want to change the value of the $app_id variable to the value of your site’s App ID.

add_filter( 'wp_footer', 'mfields_facebook_sdk' );
function mfields_facebook_sdk( $c ) {
	$app_id = '999999999999999';
	print <<<EOF
	<div id="fb-root"></div>
	<script>
	  window.fbAsyncInit = function() {
		FB.init({appId: '{$app_id}', status: true, cookie: true,
				 xfbml: true});
	  };
	  (function() {
		var e = document.createElement('script');
		e.type = 'text/javascript';
		e.src = document.location.protocol +
		  '//connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	  }());
	</script>
EOF;
}

All Together Now!

Here is all of the code in one place for easy copying. Please place it your your active theme’s functions.php file or – better yet – use it to create a custom plugin.

<?php

/* FaceBook Meta Tags
=================================================== */
function mfields_facebook_meta() {
    if ( is_singular() ) {
        $image = '';
        if ( has_post_thumbnail( get_the_ID() ) ) {
            $image = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
        }
        print "\n" . '<meta property="og:title" content="' . esc_attr( get_the_title() ) . '"/>';
        print "\n" . '<meta property="og:site_name" content="' . esc_attr( get_bloginfo() ) . '"/>';
        if ( ! empty( $image ) ) {
            print "\n" . '<meta property="og:image" content="' . esc_url( $image ) . '"/>';
        }
    }
}
add_action( 'wp_head', 'mfields_facebook_meta' );

/* FaceBook Like Link
=================================================== */
if( !function_exists( 'mfields_facebook_like_link' ) ) {
	add_filter( 'the_content', 'mfields_facebook_like_link', 20 );
	function mfields_facebook_like_link( $c ) {
		return $c . "\n\t" . '<p><fb:like href="' . get_permalink() . '" layout="button_count" font="tahoma"></fb:like></p>';
	}
}

/* FaceBook SDK
=================================================== */
if( !function_exists( 'mfields_facebook_sdk' ) ) {
	add_filter( 'wp_footer', 'mfields_facebook_sdk' );
	function mfields_facebook_sdk( $c ) {
		$app_id = '999999999999999';
		print <<<EOF
		<div id="fb-root"></div>
		<script>
		  window.fbAsyncInit = function() {
			FB.init({appId: '{$app_id}', status: true, cookie: true,
					 xfbml: true});
		  };
		  (function() {
			var e = document.createElement('script');
			e.type = 'text/javascript';
			e.src = document.location.protocol +
			  '//connect.facebook.net/en_US/all.js';
			e.async = true;
			document.getElementById('fb-root').appendChild(e);
		  }());
		</script>
EOF;
	}
}
?>

30 Comments Leave a comment

  1. Bottomless May 12, 2010 at 5:27 am

    Here’s the WordPress plugin:
    http://wordpress.org/extend/plugins/like
    No coding necessary, you can customize the look and placement of the button in the settings interface.

  2. Michael Fields May 12, 2010 at 5:36 am

    Cool Plugin Bottomless. Thanks for posting. I’ve recently been diving into the Facebook Graph API. If you know of any great resources, it would be awesome if you could share!

  3. Nicki July 1, 2010 at 11:12 pm

    Hi this is great, but it makes the site invalid when you run it through the markup validation – apparently there is no meta attribute “property” () guessing that’s a facebook flaw?

  4. Nicki July 2, 2010 at 1:04 am

    or the wrong doctype

  5. Jesse Luna July 24, 2010 at 1:57 pm

    Thanks for the code Michael. Now using the Meta tag snippet. This will become even more important now that Facebook added functionality to the Like buttons.

  6. John Flower December 18, 2010 at 10:48 am

    Hi Michael,

    fantastic! this helps a LOT. one thing though, it seems if i like my posts, it uses the wrong image. i would rather it not use an image than the wrong one. how can i fix this.

    thanks.

  7. Michael Fields December 19, 2010 at 12:16 am

    What would the correct image be? The code will use whichever image you have set as a “Featured Image” for the post. This should give you a great deal of control over which image is used when you like it on Facebook. The code will also not print a meta tag for image if you have not declared one as “Featured”. I believe in this case, Facebook will choose an image from the page to use instead.

    For best results: Always choose a featured image.

  8. John Flower December 19, 2010 at 5:46 am

    I’m not too familiar with wordpress yet. My posts are mostly images only. Some of them contain text, but the idea behind my site is poetry and illustrations. When I tested your code, the first time it added one of the share button images of a social plugin. The next share added the gravatar thumbnail. I’m not too sure what you mean by setting a featured image.

    Another thing: is there a way to turn the like button off for pages, so that it shows only in posts?

    Thanks for your detailed work. You’ve won a subscriber.

  9. Bob March 12, 2011 at 8:01 pm

    Awesome Michael, as you can see from this post http://bt.io/GnUC, I was longing for such a solution. Amazing that all Like plugins I found so far, didn’t give me the flexibility of choosing an og:image per post. Thanks!

  10. Michael Fields March 12, 2011 at 8:28 pm

    Hi Bob. Glad you found this useful! And thanks for the mention in your write up. It was interesting to read your story and hear all of the pros and cons of different solutions that you tried.

  11. Likahi March 26, 2011 at 8:17 am

    Hi, thank you the code works great. How can I add the Like
    Button to the top of a post. I’m using

    add_filter( 'the_content', 'mfields_facebook_like_link' );
    function mfields_facebook_like_link( $c ) {
        return $c . "\n\t" . '<p><fb:like href="' . get_permalink() . '" layout="button_count" font="tahoma"></fb:like></p>';
    }
    
  12. Michael Fields March 26, 2011 at 8:27 am

    It’s pretty easy, you just need to switch the order around like this:

    add_filter( 'the_content', 'mfields_facebook_like_link' );
    function mfields_facebook_like_link( $c ) {
        return '<p><fb:like href="' . get_permalink() . '" layout="button_count" font="tahoma"></fb:like></p>' . "\n\t" . $c;
    }
    
  13. Lindsey April 7, 2011 at 7:13 am

    Great code Michael, it just came in handy. I’m using the OG meta data functions. I’m wondering though, is there anyway to specify a “featured image” or post-thumbnail size? The images that are in these blog posts are quite large and when squished into Facebook’s thumnbnail size look pretty bad. I have several different sizes of thumbnails already in my functions file, I’m just wondering if I could make one that’s 100px square and somehow add it into you code for the og:image?

  14. Michael Fields April 7, 2011 at 6:02 pm

    Hi Lindsey, Thanks! This code was written a while ago. Since then, I have created a plugin which will add these meta tags for many other views in WordPress. You can download it from Github.

    One enhancement made in the plugin is the use of:

    wp_get_attachment_image_src( $post_thumbnail_id, 'thumbnail' );

    instead of :

    wp_get_attachment_url()

    Hope this helps!

  15. Derek Beck April 24, 2011 at 9:25 am

    This was extremely helpful, thanks. One question: I see facebook allows multiple og:image declarations, and each will be an option in the like/share button pop-up. So, is there any way to add a function that will check the single post for all attached pictures and then produce new meta lines declaring og:images for each?

    I know enough that when I look at http://codex.wordpress.org/Function_Reference I feel it is possible, but I’m not savvy enough to figure out how to test how many attached images there are or how to get their url’s.

    Thanks, Derek

  16. Michael Fields April 25, 2011 at 12:39 am

    You’ll want to use the get_children() function for this.

  17. Derek Beck April 26, 2011 at 12:24 am

    Thanks. Before I spend maybe 2 hours trying to figure it out, as I know php but not necessarily all of the constructs to query the WP SQL database:

    Do you by any chance happen to readily know the basic call I would use for the main line?

    For instance, I imagine it would be something like:

    $images =& get_children( ‘post_type=attachment&post_mime_type=image’ );

    if ( empty($images) ) {
    // no attachments here
    } else {
    foreach ( $images as $attachment_id => $attachment ) {

    print “\n” . ‘<meta property="og:image" content="' . esc_url( $images ) . '
    }
    }

    Does that look about right?

  18. Derek Beck April 26, 2011 at 12:25 am

    (I put one too many } at the end… typo)

  19. Derek Beck April 27, 2011 at 6:50 am

    Okay, my typo was not a typo… here’s what I tried:


    $attachedimages =& get_children( 'post_type=attachment&post_mime_type=image' );
    if ( empty($attachedimages) ) {
    // no attachments here
    print "";
    } else {
    foreach ( $attachedimages as $attachment_id => $attachment ) {
    print "\n" . '';
    //print "\n" . '';
    }
    }

    It turns out, on a post with attachments, the logic above still results in going into the code. Any ideas perchane?

  20. Derek Beck April 27, 2011 at 6:51 am

    that stripped half my code, try again:

    $attachedimages =& get_children( ‘post_type=attachment&post_mime_type=image’ );
    if ( empty($attachedimages) ) {
    // no attachments here
    print ““;
    } else {
    foreach ( $attachedimages as $attachment_id => $attachment ) {
    print “\n” . ”;
    }
    }

    It turns out, on a post with attachments, the logic above still results in going into the code. Any ideas perchane?

  21. Derek Beck April 29, 2011 at 7:18 am

    Okay, sorry to have put a bunch of junk posts to your blog. Here’s the code I’m using that is very close, but not quite what I need:

    http://wordpress.org/support/topic/simple-codexphp-coding-question-get_children?replies=2

  22. Michael Fields May 3, 2011 at 3:08 pm

    There is a better, more robust solution to the Open Graph Meta tags for WordPress that I have uploaded to Github: https://github.com/mfields/mfields-opengraph-meta-tags/

  23. Derek Beck May 3, 2011 at 7:11 pm

    Looks quite robust indeed. One note: you are missing the closing php tag at the end.

  24. Michael Fields May 3, 2011 at 7:12 pm

    Thanks! Only thing is, you do not need a closing php tag at the end :)

  25. Derek Beck May 3, 2011 at 7:15 pm

    Ah. Is that because it is assumed when you call (include) a separate php file?

  26. Michael Fields May 3, 2011 at 7:19 pm
  27. Matthew July 22, 2011 at 4:17 am

    I still like this code better than any plugin I’ve found, thanks.

    The lint tool show two errors:
    Required Property Missing og:type is required
    Required Property Missing og:url is required

    any ideas on how to fix?

  28. Michael Fields July 22, 2011 at 5:25 am

    Thanks Matthew! There is better code on Github which is much more evolved than the code posted here. You can chek it out by clicking the following link:

    Open Graph Meta Tags Hosted on Github

  29. Matthew July 22, 2011 at 5:32 am

    I explored your plugin after I wrote the comment. I used the manual code above and edited it slightly to get the duplicate meta info gone, once I installed your plugin. if you get a chance, I’d love to get your opinion on if I’ve done it right.
    http://tothevillagesquare.org/blog is the main blog page. the linter doesn’t show errors on individual posts, providing I’ve aded a featured image. my code looks like this on the theme functions file:

    /* FaceBook Meta Tags
    =================================================== */
    function mfields_facebook_meta() {
        if ( is_singular() ) {
            $image = '';
            if ( has_post_thumbnail( get_the_ID() ) ) {
                $image = wp_get_attachment_url( get_post_thumbnail_id( get_the_ID() ) );
            }
            
            if ( ! empty( $image ) ) {
                print "\n" . '<meta property="og:image" content="' . esc_url( $image ) . '"/>';
            }
        }
    }
    add_action( 'wp_head', 'mfields_facebook_meta' );
     
    /* FaceBook Like Link
    =================================================== */
    if( !function_exists( 'mfields_facebook_like_link' ) ) {
        add_filter( 'the_content', 'mfields_facebook_like_link' );
    function mfields_facebook_like_link( $c ) {
        return '<p><fb:like href="' . get_permalink() . '" layout="button_count" font="tahoma"></fb:like></p>' . "\n\t" . $c;
    }
    }
     
    /* FaceBook SDK
    =================================================== */
    if( !function_exists( 'mfields_facebook_sdk' ) ) {
        add_filter( 'wp_footer', 'mfields_facebook_sdk' );
        function mfields_facebook_sdk( $c ) {
            $app_id = 'TACOTACOTACOTACO';
            print <<<EOF
            <div id="fb-root"></div>
            <script>
              window.fbAsyncInit = function() {
                FB.init({appId: '{$app_id}', status: true, cookie: true,
                         xfbml: true});
              };
              (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                  '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
              }());
            </script>
    EOF;
        }
    }
  30. AM November 18, 2011 at 7:09 pm

    Hi – I copied the code from GitHub without making any changes into my site’s functions.php file but my site crashes every time. Should I be making any changes to it? I did get an App ID but don’t see where I need to add it to the code on GitHub. Thank you,
    Newbie

Share your thoughts

Fork me on GitHub