Creating a Wordpress plugin: Add the new Facebook Like button to your posts

——————
Note: Here is the latest version of the Facebook Like Wordpress Plugin for the impatient (and people not interested in the technical details but just looking for a solution working out of the box).

There is also the Official Wordpress page (from which you should rate the plugin and report it works, thanks).

This blog post is about the process of creating the plugin itself, so if you use the plugin directly you don’t have anything else to do than just installing it.
No coding necessary.
Otherwise you would add things manually and then the plugin would do the same again.
Jump to section 7/ Installation of the plugin if you just want to use the final product working out of the box.
Check also section 8/ Customize the plugin for help on configuring it when installed.
——————

Writing a Wordpress plugin is fairly simple provided you know PHP and follow the well documented process at wordpress.org.

If you’re in a hurry and just want a simple functionality, this guide is what you need.

Here’s a shortened version on how to create a Wordpress plugin that will add the new Facebook “Like” button announced yesterday at f8 to your posts and/or pages.

Facebook new Like button

Simple yet customizable as we’ll still provide a settings page for the plugin.

Facebook new Like button Wordpress plugin settings

1/ Optional Preparation

You can write a plugin and release it without submitting it to the official Wordpress directory.

Submitting your plugin to the Wordpress directory means your plugin must be release under GPLv2, so be aware of that before hand if it bothers you.

Some benefits of submitting to the directory are:
- faster distribution (users can find it easily)
- free SVN hosting
- packaging of the different versions
- access to analytics (number of downloads, …)

If you intend to submit your plugin to the directory, it may be a good idea to first look up which names are available as you may want to name your files and functions according to this name.
Check out the Wordpress plugin SVN to see what’s already taken.

2/ Create the plugin folder

bash# cd ~/wordpress/wp-content/plugins/
bash# mkdir like
bash# cd like/
bash# touch readme.txt
bash# touch tt_like_widget.php

We really need only two files:
- the readme file to describe the plugin,
- the actual code of the plugin in the php file (name it whatever you want).

3/ Write the Readme file

A basic Readme file looks like this:

=== Like ===
Contributors: bottomlessinc
Donate link: http://blog.bottomlessinc.com/
Tags: share, facebook, like, button, social, bookmark, sharing, bookmarking, widget
Requires at least: 2.3
Tested up to: 2.9.2
Stable tag: 1.0

The Facebook Like Button Widget adds a 'Like' button to your Wordpress blog posts.

== Description ==
Let your readers quickly share your content on Facebook with a simple click.

== Installation ==

1. Upload `tt_like_widget.php` to the `/wp-content/plugins/` directory
1. Activate the plugin through the 'Plugins' menu in WordPress
1. (Optional) Customize the plugin in the Settings > Like menu

== Frequently Asked Questions ==

= Is Like free? =

Yes

== PHP Version ==

PHP 5+ is preferred; PHP 4 is supported.

== Changelog ==

= 1.0 =
Stable version

You can get more information on the readme file with this more elaborated example.
Wordpress also provides a readme validator the way W3C does for XHTML validation.

4/ Write the PHP file

Only one function will be called in the file, the init function:

tt_like_init();

It does three main things:
- register and retrieve the parameters of your plugin if you have any (you will be able to set those in the settings page)
- register your own function to be called when an event happens, here an event called ‘the_content’ called every time the content of the post is rendered. Our plugin here will just append some content at the end of the post content.
- register your own function to be called to render the settings page in your Wordpress admin panel so you can customize your plugin.

function tt_like_init()
{
    add_option('tt_like_width', '450');
    add_option('tt_like_layout', 'standard');
    add_option('tt_like_showfaces', 'true');

    $tt_like_settings['width'] = get_option('tt_like_width');
    $tt_like_settings['layout'] = get_option('tt_like_layout');
    $tt_like_settings['showfaces'] = get_option('tt_like_showfaces') === 'true';

    add_filter('the_content', 'tt_like_widget');
    add_filter('admin_menu', 'tt_like_admin_menu');
}

The add_option function is provided by the Wordpress API and registers the default values of your options.
The previously saved setting are retrieved using get_option() and stored in our global variable we named ‘tt_like_settings’.
Our function tt_like_widget() will get called every time the content of the post needs to be rendered as we registered it with the add_filter() function.
In a similar manner, tt_like_admin_menu() will get called to render the settings page in the Wordpress admin interface.

The tt_like_widget() function is pretty straight forward: just append whatever you want to append to the $content variable.

function tt_like_widget($content)
{
     $showfaces = ($tt_like_settings['showfaces']=='true')?"true":"false";
     $url = urlencode(get_permalink()) . "&layout="  . $tt_like_settings['layout']
                                . "&show_faces=" . $showfaces
                                . "&width=" . $tt_like_settings['width'];
     $button = '<iframe src="http://www.facebook.com/plugins/like.php?href='.$url.'" scrolling="no" frameborder="0" allowTransparency="true" style="border:none; overflow:hidden; width:'.$tt_like_settings['width'].'px; height: 50px"></iframe>';
     $content .= $button;
     return $content;
}

Here we build a Facebook Like button which is just an iframe pointing to a Facebook URL having the URL of the current post as parameter.
It means we need to retrieve the URL of the current post dynamically, this is done using get_permalink()
This is also the place we use our settings to produce a Facebook Like button customized according to the settings on the admin page.

And now for the settings on the admin page. We basically build an html form that will record the user preferences.

function tt_plugin_options()
{
    $tt_like_layouts = array('standard', 'button_count');

    <div class="wrap">
    <h2>Facebook Like Button</h2>

    <form method="post" action="options.php">
    <?php
        if (tt_get_wp_version() < 2.7) {
            wp_nonce_field('update-options');
        } else {
            settings_fields('tt_like');
        }
    ?>

    <table class="form-table">
        <tr valign="top">
            <th scope="row"><?php _e("Width:", 'tt_like_trans_domain' ); ?></th>
            <td><input type="text" name="tt_like_width" value="<?php echo get_option('tt_like_width'); ?>" /></td>
        </tr>
        <tr>
            <th scope="row"><?php _e("Layout:", 'tt_like_trans_domain' ); ?></th>
            <td>
                <select name="tt_like_layout">
                <?php
                    $curmenutype = get_option('tt_like_layout');
                    foreach ($tt_like_layouts as $type)
                    {
                        echo "<option value=\"$type\"". ($type == $curmenutype ? " selected":""). ">$type</option>";
                    }
                ?>
                </select>
        </tr>
        <tr>
            <th scope="row"><?php _e("Show faces:", 'tt_like_trans_domain' ); ?></th>
            <td><input type="checkbox" name="tt_like_showfaces" value="true" <?php echo (get_option('tt_like_showfaces') == 'true' ? 'checked' : ''); ?>/></td>
        </tr>
    </table>

     <?php if (tt_get_wp_version() < 2.7) : ?>
       <input type="hidden" name="action" value="update" />
       <input type="hidden" name="page_options" value="tt_like_width, tt_like_layout, tt_like_verb, tt_like_colorscheme, tt_like_showfaces"/>
    <?php endif; ?>

    <p class="submit">
    <input type="submit" name="Submit" value="<?php _e('Save Changes') ?>" />
    </p>

    </form>
    </div>
}

Here we have some code for an input box, a dropdown menu and a checkbox as example.
There is some handling for earlier version of Wordpress.
Refer to the options page help for further information.
The _e() function is here for internationalization.

5/ Submit your plugin to the Wordpress directory

Submit your new plugin to the directory by providing a unique name for it.

You will then be able to upload it to the SVN repository.

6/ Check in your code in the SVN repository

After Wordpress approves your plugin (it took 3 days for this one), you can check your code in the provided SVN link.

bash# mkdir ~/my_wp_plugin
bash# cd ~/my_wp_plugin
bash# svn co http://svn.wp-plugins.org/like
A    like/trunk
A    like/branches
A    like/tags
Checked out revision 233010.
bash# cp ~/wordpress/wp-content/plugins/like/readme.txt trunk/
bash# cp ~/wordpress/wp-content/plugins/like/tt_like_widget.php trunk/
bash# svn add trunk/*
A         trunk/readme.txt
A         trunk/tt_like_widget.php
bash# svn ci -m "First stable version"
Authentication realm: <http://svn.wp-plugins.org:80> WordPress.org Subversion
Username: bottomlessinc
Password for 'bottomlessinc': ****
Adding         trunk/readme.txt
Adding         trunk/tt_like_widget.php
Transmitting file data ..
Committed revision 233012.
bash#

Now you can tag the revision of the plugin as your first version.

bash# svn cp trunk tags/1.0
A         tags/1.0
bash# svn ci -m "Tagging v1.0"
Adding         tags/1.0
Adding         tags/1.0/readme.txt
Adding         tags/1.0/tt_like_widget.php
Committed revision 233013.
bash#

Now that your code is checked in with the mandatory readme.txt file and you tagged the version 1.0 of your SVN to match the Stable tag: 1.0 in readme.txt, Wordpress will do all the rest and package it for you.

It will be available to a URL resembling http://wordpress.org/extend/plugins/like making it accessible to all Wordpress user and providing you download statistics and feedbacks from users.

You can also promote your plugin further by submitting it to wp-plugins.

7/ Installation of the plugin

Here is the complete code for the widget:

Facebook Like Wordpress Plugin (Latest Version)

Unzip it in your plugin directory.

bash# cd ~/wordpress/wp-content/plugins/
bash# wget http://blog.bottomlessinc.com/wp-content/uploads/2010/04/like.zip
bash# unzip like.zip

Then go to the Wordpress admin dashboard, activate it, and optionally customize it in the settings page.

8/ Customize the plugin

The plugin works out of the box without configuration as it uses the IFRAME version of the button.

Optionally you can use the XFBML version but it requires more setup and a better knowledge of the Facebook platform as you will need to create a Facebook Application and enter its App ID in the settings page of the plugin.

Which one to choose, IFRAME or XFBML?

It really depends on how technical you are.
If you are not, stick with the default settings using the IFRAME version.
If you are technical you can venture in the XFBML version, but even there you will hit snags as Facebook is notorious for producing unstable Javascript and not getting things to work the first time (a daily struggle when you develop Facebook applications).

With XFBML, the user who clicked the Like button can add a comment that will be attached to the post on his profile.

Facebook XFBML Like button comment

The benefit of using XFBML is purely real estate: provided the user not only clicks the button but adds a comment, the profile post will now include the image you entered in the Settings of the plugin along with an excerpt of the article.

For comparison here is the one liner you will see if using IFRAME or if using XFBML when the user did not add a comment…:
Facebook Like button wallpost IFRAME

… and here is the profile post the user will generate when adding a comment with the XFBML version of the button:
Facebook Like button wallpost XFBML

Even though Facebook provides a simplified interface to generate a new Application, it doesn’t work right away.

When I first set it up I had this message when clicking the button:

The application ID specified within the “fb:app_id” meta tag is not allowed on this domain. You must setup the Connect Base Domains for your application to include this domain.
Facebook ©2010

When editing the settings of the Application itself, I couldn’t see anything wrong, and hit the “Save Changes” button without modifying anything.
Surprisingly it raised this error, refusing to save the (non existing) changes:

Validation failed.

Connect URL must point to a directory (i.e., end with a “/”) or a dynamic page (i.e., have a “?” somewhere).

In this case just edit the Application, go to the “Connect” tab and in the first field called “Connect URL”, make sure your website ends with a forward slash.
For instance I had to manually change my Facebook Connect URL from “http://bottomlessinc.com” to “http://bottomlessinc.com/” to make things work.

And even after that, when using the XFBML version the button doesn’t show up in around 20% of the page refresh.
That’s why sticking with the default IFRAME version is more reliable.

There is also a chance that adding a slash to your Connect URL will solve the problem of the Like button blinking (showing up as pressed then right away as unpressed).
During this blinking of the button you can see the message “You like http://example.com” which disappears also right away.

If you use the XFBML version of the plugin, you must provide the numerical Facebook ID of the Facebook user you will use to manage the pages.
Otherwise people clicking on the Like button will receive this error:

You failed to provide a valid list of administators. You need to supply the administors using either a “fb:app_id” meta tag, or using a “fb:admins” meta tag to specify a comma-delimited list of Facebook users.

Did you find this post useful? Like it on Facebook :-) and Spare a few cents:

Tags: , , ,

397 Responses to “Creating a Wordpress plugin: Add the new Facebook Like button to your posts”

  1. Ok, if you have that problem with Like and Simple:Press allow in Simple:Press the following 2 options:
    1. Load js in footer
    2. Allow multiple loads
    from the WP integration tab. Sorry for the spam!

  2. Ryan says:

    Seems that the support for this plugin is no longer.

    Possibly due to not enough donations lol. If anyone does have a solution to this “You failed to provide a valid list of administators…..” error or a plugin that works please let us know thanks

  3. Use on your WordPress site for a while and recently stopped working. I got an error when you click on eg “You do not have a current list of administrators to Administors is necessary to use one.” FB: app_id “Providing a meta tag, or using” FB: Administrators tag “comma-separated list of Facebook users to enter” I have never in this area, or in the article, as shown in Avanced users, and not something I wanted to break. I have a Facebook ID numbers, but in vain.

  4. Gavin Thorn says:

    Firstly, thanks for a great plugin.

    I’m using the ALO EasyMail newsletter plugin and an issue I have is the Like button appearing on the email that gets sent. A workaround is to prevent the button code from being inserted if there is no permalink (as in the case of an email). The modification is very simple and affects the area of code around line 377 in tt_like_widget.php as follows…

    $purl = get_permalink(); <– existing code
    if(!$purl) return $content;

    Best regards,
    Gavin

  5. Hannah says:

    Hey, I recently read that with the use of iframes, facebook tracks your visit to a site with a like button, even if you don’t click it. Regardless of whether you have a facebook account or not. I suppose it is the same with the share button.

    A german website, heise.de, implemented a two-click-solution, where your presence on the site will only be send to facebook when you actually use a facebook button.

    I think that’s an awesome idea, so now I am looking for a plugin that could do this on wordpress. So far to no avail.

    heise.de even provides the code, but unfortunatelly I don’t know the language and grammar to program my own plugin. But maybe you like the idea too and like to implement this into yours!

    This is a link to the open source code/plug in heise.de provides:
    http://www.heise.de/extras/socialshareprivacy/

    unfortunatelly the documentation is in german, but the plugin itself is probably understandable to you?
    http://www.heise.de/extras/socialshareprivacy/

    And this is the – also german – article where I got all this from
    http://www.heise.de/ct/artikel/2-Klicks-fuer-mehr-Datenschutz-1333879.html

    I hope this is somehow interesting to you, in any case, thanks for reading and kind regards!

  6. prk says:

    Is it possible with this plugin to make the connection described in http://developers.facebook.com/docs/reference/plugins/like/: “Your page will appear in the “Likes and Interests” section of the user’s profile, and you have the ability to publish updates to the user”? I guess it have to be XFBMLversion then, and that you have to create a App ID?

    I manage to get the page to appear in the “Likes and Interests” section with the instructions from developers.facebook.com, but that is from a ordinary .html document, and not Wordpress.

  7. Fred says:

    Hi there,

    also having the random image published on facebook… wondering how can I change the image that shows up when someone like my post…

    many thanks for the great plugin!

  8. Mattias says:

    Quote:
    “@Michael
    For the language, you Facebook language setting will determine how the button if displayed (Like or Liebe,…) and you Wordpress settings will determine how the plugin configuration page in the Wordpress admin dashboard is being displayed.
    If you want the button to read “Liebe” instead of “Like”, change you Facebook language settings (but it will display it only for you, the beauty is that others with different language settings will still see “Like” written in their own language)”

    I have problem with this. I’m from Sweden, I have set my Facebook to Swedish. My wordpress site is in Swedish and so is the Adminpages of Wordpress. I have even translated this plugin into Swedish. But the Likebutton is still in English under my posts. That doesn’t look good on my Swedish site.

    I used the Facebook Like plugin before and there you can choose what language you want to use in the Pluginsettings, but it didn’t work 100% like I wanted it. Yours does, except this little problem. Any ideas?

  9. art says:

    I made og:title with custom field ‘facebook_image’ and then edit plugin file:

    $image = trim(get_post_meta(get_the_ID(), ‘facebook_image’, true));
    if($image!=”) {
    echo ”.”\n”;
    }

  10. Aaron says:

    Hi, my like button was working fine until today but now I’m getting an error and when I run it through the facebook developer debug site it says:

    Error Updating Page: Value cannot be null (Value given: null) TAAL[BLAME_file]

    Any thoughts on what I need to do to fix it?

    Thanks, Aaron

  11. Lee says:

    Very handy and useful plugin, but you really need to have the ability to exclude the Like button from a particular post (e.g. private posts, etc.). I have looked everywhere for a solution and can’t find a way to do this. Any chance a short code will be coming for this in the future?

    Regards,
    Lee

  12. Jessica says:

    We’re using your wordpress Like plugin and it works fine, but the image it pulls when it posts to facebook is random and usually wrong. is there a way to control the image it chooses to post since this is important in what people click on?

  13. katie says:

    Hello, I use this plugin and I get this error in FB Lint:

    The og:description property should be explicitly provided, even if a value can be inferred from other tags.

    I have checked the Use Excerpt as Description option. How do I get rid of this error?

  14. Jennifer says:

    Plug in works..except when someone likes a post -it posts to face book with a Twitter “t” Icon. How do i fix that?

  15. Steve says:

    I’m happy with this plugin but confused about one thing: I want to get an og:image metatag pointing to something that Facebook will always try to use. The FB guidelines say this:

    The og:image is the URL to the image that appears in the Feed story. The thumbnail’s width AND height must be at least 50 pixels, and cannot exceed 130×110 pixels. The ratio of both height divided by width and width divided by height (w/h, h/w) cannot exceed 3.0. For example, an image of 126×39 pixels will not be displayed, as the ratio of width divided by height is greater than 3.0 (126/39 = 3.23). Images will be resized proportionally.

    I know this is about FB and not about the Like plugin, but what is the suggested workflow when creating a post? Do I need to create a separate media item that is the thumbnail for the post. How do I tell Like to use that thumbnail for the og:image tag. Or can I just tell Like to use one of the images in my post? As someone remarked above, FB randomly selects background graphics — the twitter icon in my case — and it really looks stupid.

    Thanks for this plugin.

  16. Dean says:

    hey guys – great plugin, simple and works!

    is there a SHORTCODE???
    or how can i add it to excerpts on the homepage?

    thanks a lot

  17. [...] Facebook Like plugin for WordPress, I recommend BottomlessInc’s Like plugin.  He even has a tutorial on how he made the Like plugin itself, but let’s focus on the task at hand: doing it [...]

  18. Alex Ben says:

    Great plugin but I have ONE QUESTION.

    I would like to insert some code just AFTER content (single.php) and BEFORE like button. But even I add a hack to functions.php a code is being inserted AFTER like button.

    Is it possible to insert some code just after content but before like button? Or can I insert like button manualy?

  19. Cedric says:

    Is there a way to display manually the like button in a template theme? With a shortcode or a function? I tried with the tt_like_widget($content) but with no success: it displays a like button but there is still another button added automatically…

  20. Kingsley C. says:

    This is good. It works great. Thanks, I used this plugin on my site.

  21. art says:

    hi! good plugin!
    but after some plugins, which use add_filter(‘the_content’, …
    get_the_excerpt inside like plugin show only content of that plugins (for example related posts plugin)

    even the_content() inside your plugin return not only related posts plugin content without content of post

  22. Cospefogo says:

    Hi there!

    Is there a way to manually insert the like button calling it as a PHP function, as many other plugins out there permit? I want to include it after all the procedures I run in my loops… the title, the content, featured image, custom fields, meta fields… and in the very bottom, the like button.

    On the way it works right out of the box, the facebook like goes directly inside/in the bottom of the content area… Thanks! C.

Leave a Reply