Facebook Like Box Widget for WordPress

Facebook Like Box Widget for WordPress

Tutorial Details
  • Program: WordPress
  • Version: 3.1
  • Difficulty: Easy
  • Estimated Completion Time: 30 minutes

If your website has a Facebook page then it’s a good idea to promote this to your readers by displaying a Facebook like box on the sidebar of the blog.

In this tutorial we are going to create a WordPress widget which displays your Facebook like box. With this WordPress widget you will have the option to display the box header, show your latest fans and show your latest Facebook stream.


Facebook Pages

Facebook Pages have been around for a while now and they have recently been converted to use the new timeline feature to bring even more exposure to your previous posts on your profile.

A Facebook Page is the same as a personal page but you can not friend other people, this is because Facebook Pages are for businesses to connect with their customers.

Facebook Pages give you a more dynamic relationship with the public figures and organizations you are interested in.

If you have your own business you too can create your own Facebook Page.


Facebook Like Box

A Facebook like box is a social plugin which enables Facebook Page owners to display a like button and a status stream on their own website.

The like box means visitors to your site can:

  • See how many people like the page and which of their friends already like this page.
  • View your recent status updates.
  • Like your Facebook Page without leaving your site.

Here is an example of Wptuts+’s Facebook like box.

To create a Facebook Like Box for your Facebook page you need to register a Facebook app to be able to use the Facebook open graph API.

Now you see what the Facebook like box is we can understand how to turn this into a WordPress widget.


WordPress Widgets

Before we start coding the widget we need to understand what a WordPress widget is and how we can use the WordPress Widget API to easily create WordPress widgets.

A WordPress widget is a piece of PHP code which will run inside a WordPress sidebar.

A WordPress sidebar is a registered area in your theme where you can add WordPress widgets.

WordPress widgets can easily be added to sidebars by going to the Widget page in the Dashboard and navigate to Appearance -> Widgets. From this Widgets page you are able to drag and drop widgets into a sidebar of your choice. The widget should have some sort of Admin form so you can edit the data shown by the widget.


WordPress WP_Widget

To create a WordPress widget all you need to do is inherit from the standard WP_Widget class and use some of its functions.

There are three main functions that need to be used for the widget to work these functions are form(), widget() and update().

The WP_Widget class is located in wp-includes/widgets.php.


WordPress Starter Widget

Below is the boilerplate of a WordPress widget, when you create a new widget just copy and paste the below code as a starting point for your widget.

/**
 * Adds Foo_Widget widget.
 */
class Foo_Widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {
		parent::__construct(
			'foo_widget', // Base ID
			'Foo_Widget', // Name
			array( 'description' => __( 'A Foo Widget', 'text_domain' ), ) // Args
		);
	}

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );
		$title = apply_filters( 'widget_title', $instance['title'] );

		echo $before_widget;
		if ( ! empty( $title ) )
			echo $before_title . $title . $after_title;
		?>Hello, World!<?php
		echo $after_widget;
	}

	/**
	 * Sanitize widget form values as they are saved.
	 *
	 * @see WP_Widget::update()
	 *
	 * @param array $new_instance Values just sent to be saved.
	 * @param array $old_instance Previously saved values from database.
	 *
	 * @return array Updated safe values to be saved.
	 */
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = strip_tags( $new_instance['title'] );

		return $instance;
	}

	/**
	 * Back-end widget form.
	 *
	 * @see WP_Widget::form()
	 *
	 * @param array $instance Previously saved values from database.
	 */
	public function form( $instance ) {
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		}
		else {
			$title = __( 'New title', 'text_domain' );
		}
		?>
		<p>
		<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
		</p>
		<?php
	}

} // class Foo_Widget

Creating Facebook Like Box Widget

We are going to create a WordPress widget to allow you to easily add and change a Facebook like box on your WordPress blog.

The benefit of using a widget is for the flexibility it will give you. The choice that you have on your Facebook like box allows you to completely change the functionality just by placing different attributes on the like box.

The Facebook like box takes the following attributes:

  • data-href – The URL to your Facebook page.
  • data-width – The width of the like box.
  • data-show-faces – A true or false value which decides if you will show people who like your page.
  • data-stream – A true or false value which decides if you will show your latest status updates.
  • data-header – A true or false value which decides if you will show the find us on Facebook bar.

These are the options which we need to make sure the user can change in the widget admin screen, so they can change the look of the like box directly in the WordPress dashboard.

Now we know what to expect from the Facebook like box we can start coding.

Facebook Widget Constructor

First we are going to register the widget on the widget_init action.

/*
 * Plugin Name: Paulund Facebook Like Box
 * Plugin URI: http://www.paulund.co.uk
 * Description: A widget that a facebook like box for your website
 * Version: 1.0
 * Author: Paul Underwood
 * Author URI: http://www.paulund.co.uk
 * License: GPL2

    Copyright 2012  Paul Underwood

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License,
    version 2, as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details. 
*/

/**
 * Register the Widget
 */
add_action( 'widgets_init', create_function( '', 'register_widget("pu_facebook_widget");' ) );

The register_widget function will call the pu_facebook_widget class. In the constructor we can create the widget by passing through arguments to the WP_Widget constructor.

/**
 * Create the widget class and extend from the WP_Widget
 */
class pu_facebook_widget extends WP_Widget {

	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {

		parent::__construct(
			'pu_facebook_widget',		// Base ID
			'Facebook Like Box',		// Name
			array(
				'classname'		=>	'pu_facebook_widget',
				'description'	=>	__('A widget that displays a facebook like box from your facebook page.', 'framework')
			)
		);

	} // end constructor
}

Widget Function

The widget function is called to output the widget in the sidebar. This is where we need to collect the data input from the user on the dashboard and display the widget on the website.

Use the following function to display your Facebook like box.

	/**
	 * Front-end display of widget.
	 *
	 * @see WP_Widget::widget()
	 *
	 * @param array $args     Widget arguments.
	 * @param array $instance Saved values from database.
	 */
	public function widget( $args, $instance ) {
		extract( $args );

		/* Our variables from the widget settings. */
		$this->widget_title = apply_filters('widget_title', $instance['title'] );

		$this->facebook_id = $instance['app_id'];
		$this->facebook_username = $instance['page_name'];
		$this->facebook_width = $instance['width'];
		$this->facebook_show_faces = ($instance['show_faces'] == "1" ? "true" : "false");
		$this->facebook_stream = ($instance['show_stream'] == "1" ? "true" : "false");
		$this->facebook_header = ($instance['show_header'] == "1" ? "true" : "false");

		add_action('wp_footer', array(&$this,'add_js'));

		/* Display the widget title if one was input (before and after defined by themes). */
		if ( $this->widget_title )
			echo $this->widget_title;

		/* Like Box */
		?>
			<div class="fb-like-box"
				data-href="http://www.facebook.com/<?php echo $this->facebook_username; ?>"
				data-width="<?php echo $this->facebook_width; ?>"
				data-show-faces="<?php echo $this->facebook_show_faces; ?>"
				data-stream="<?php echo $this->facebook_stream; ?>"
				data-header="<?php echo $this->facebook_header; ?>"></div>
		<?php
	}

You may have noticed we add an action to the wp_footer to run the function add_js. This is where you will need to add the Facebook JavaScript to get the like box to work correctly.

/**
 * Add Facebook javascripts
 */
public function add_js() {
	echo '<div id="fb-root"></div>
		<script>(function(d, s, id) {
			var js, fjs = d.getElementsByTagName(s)[0];
			if (d.getElementById(id)) return;
			js = d.createElement(s); js.id = id;
			js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1&appId='.$this->facebook_id.'";
			fjs.parentNode.insertBefore(js, fjs);
		}(document, \'script\', \'facebook-jssdk\'));</script>';
}

Update Function

The update function is used to update the WordPress database when the widget admin form is submitted.

This is where you will need to place any validation needed on the values from the form. This takes 2 parameters, an array of values sent to be saved and an array of values which are currently stored. The return of this function will be the new values stored in the database.

/**
 * Sanitize widget form values as they are saved.
 *
 * @see WP_Widget::update()
 *
 * @param array $new_instance Values just sent to be saved.
 * @param array $old_instance Previously saved values from database.
 *
 * @return array Updated safe values to be saved.
 */
function update( $new_instance, $old_instance ) {
	$instance = $old_instance;

	/* Strip tags for title and name to remove HTML (important for text inputs). */
	$instance['title'] = strip_tags( $new_instance['title'] );
	$instance['app_id'] = strip_tags( $new_instance['app_id'] );
	$instance['page_name'] = strip_tags( $new_instance['page_name'] );
	$instance['width'] = strip_tags( $new_instance['width'] );

	$instance['show_faces'] = (bool)$new_instance['show_faces'];
	$instance['show_stream'] = (bool)$new_instance['show_stream'];
	$instance['show_header'] = (bool)$new_instance['show_header'];

	return $instance;
}

Form Function

facebook_like_box

The form function is used to create the form on the widget dashboard. This will need to be pre-populated with the current values in the database and make it easy for the user to change the values to change the widget behaviour.

/**
 * Create the form for the Widget admin
 *
 * @see WP_Widget::form()
 *
 * @param array $instance Previously saved values from database.
 */
function form( $instance ) {

	/* Set up some default widget settings. */
	$defaults = array(
		'title' => $this->widget_title,
		'app_id' => $this->facebook_id,
		'page_name' => $this->facebook_username,
		'width' => $this->facebook_width,
		'show_faces' => $this->facebook_show_faces,
		'show_stream' => $this->facebook_stream,
		'show_header' => $this->facebook_header
	);

	$instance = wp_parse_args( (array) $instance, $defaults ); ?>

	<!-- Widget Title: Text Input -->
	<p><label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'framework') ?></label>
	<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $instance['title']; ?>" /></p>

	<!-- App id: Text Input -->
	<p><label for="<?php echo $this->get_field_id( 'app_id' ); ?>"><?php _e('App Id', 'framework') ?></label>
	<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'app_id' ); ?>" name="<?php echo $this->get_field_name( 'app_id' ); ?>" value="<?php echo $instance['app_id']; ?>" /></p>

	<!-- Page name: Text Input -->
	<p><label for="<?php echo $this->get_field_id( 'page_name' ); ?>"><?php _e('Page name (http://www.facebook.com/[page_name])', 'framework') ?></label>
	<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'page_name' ); ?>" name="<?php echo $this->get_field_name( 'page_name' ); ?>" value="<?php echo $instance['page_name']; ?>" /></p>

	<!-- Width: Text Input -->
	<p><label for="<?php echo $this->get_field_id( 'width' ); ?>"><?php _e('Width', 'framework') ?></label>
	<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'width' ); ?>" name="<?php echo $this->get_field_name( 'width' ); ?>" value="<?php echo $instance['width']; ?>" /></p>

	<!-- Show Faces: Checkbox -->
	<p><label for="<?php echo $this->get_field_id( 'show_faces' ); ?>"><?php _e('Show Faces', 'framework') ?></label>
	<input type="checkbox" class="widefat" id="<?php echo $this->get_field_id( 'show_faces' ); ?>" name="<?php echo $this->get_field_name( 'show_faces' ); ?>" value="1" <?php echo ($instance['show_faces'] == "true" ? "checked='checked'" : ""); ?> /></p>

	<!-- Show Stream: Checkbox -->
	<p><label for="<?php echo $this->get_field_id( 'show_stream' ); ?>"><?php _e('Show Stream', 'framework') ?></label><input type="checkbox" class="widefat" id="<?php echo $this->get_field_id( 'show_stream' ); ?>" name="<?php echo $this->get_field_name( 'show_stream' ); ?>" value="1" <?php echo ($instance['show_stream'] == "true" ? "checked='checked'" : ""); ?> /></p>

	<!-- Show Header: Checkbox -->
	<p><label for="<?php echo $this->get_field_id( 'show_header' ); ?>"><?php _e('Show Header', 'framework') ?></label>
	<input type="checkbox" class="widefat" id="<?php echo $this->get_field_id( 'show_header' ); ?>" name="<?php echo $this->get_field_name( 'show_header' ); ?>" value="1" <?php echo ($instance['show_header'] == "true" ? "checked='checked'" : ""); ?> /></p>

	<?php
}

You do not need to add a submit button as WordPress will automatically add it for you.


Download

That's all you need to create a WordPress plugin which creates a widget to display your Facebook like page. All you have to do now is install the plugin, activate it, add the widget to a sidebar and fill out the form with your page details.

You can download this plugin from WordPress.org: Download Facebook Like Box Plugin

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://daveismyname.com Dave

    Excellent tutorial looks very useful.

    Another way is using a little javascript and placing the code below in a widget granted its not as flexible.

    Just change you-id-here.

    FB.init(“1690883eb733618b294e98cb1dfba95a”);
    <fb:fan profile_id="your-id-here" stream="0" connections="8" logobar="0" width="190" height="350" css="?1″ rel=”stylesheet” type=”text/css”>

    • http://daveismyname.com Dave

      Ah I forgot to replace the brackets lets try that again.

      <script type=”text/javascript” src=”http://connect.facebook.net/en_US/all.js#xfbml=1″></script>
      <script type=”text/javascript”>FB.init(“1690883eb733618b294e98cb1dfba95a”);</script>
      <fb:fan profile_id=”your-id-here” stream=”0″ connections=”8″ logobar=”0″ width=”190″ height=”350″ css=”<?php bloginfo(‘stylesheet_url’); ?>?1″ rel=”stylesheet” type=”text/css”></fb:fan>

      • http://www.paulund.co.uk Paul
        Author

        Hi Dave

        Yea I’ve seen that option. Do you still get all the same options for showing fans, showing number of likes, showing header box etc?

        Do you know which one Facebook suggests we should be using?

  • Pingback: Facebook Like Box Widget for WordPress | Shadowtek Hosting and Design Solutions

  • Pingback: Create A Facebook Like Box Guest Post WPTuts | web design resources | freebies | tutorials

  • http://www.customicondesign.com CUSTOM ICON DESIGN

    very useful to me. great tutorial for the widget. I have learned a lot from this article.

    thanks.

  • Pingback: WordPress.com Gets New Notifications Tab, Toolbar Button | Open Knowledge

  • http://www.wpsquare.com Bharat Chowdary

    Great tutorial Paul, between there is a typo in website link used in Author Box.

    • http://www.paulund.co.uk Paul
      Author

      Thanks Bharat hope you found it useful, the link should be fixed now.

  • http://zantutos.com Rodrigo Zandonadi

    Paul
    When I install the widget error on page 226, which has a second ‘}’. What goes wrong?

    • http://zantutos.com Rodrigo Zandonadi

      The widget shows error, not to enter the information. Does not display the contents of the fanpage.

  • Cara Jeanne

    Just curious, why would I want to add a FB widget instead of using the code from FB into a html widget in WP? I am wondering what the benefits may be, thank you.

    • http://www.paulund.co.uk Paul
      Author

      Hello Cara

      The benefit of this is that it allows you to customise the look of it directly in the widget dashboard. So if you need to hide the stream or hide the header or change the width of the plugin then instead of going back to facebook all you need to do is open your widget dashboard and change the settings.

      Hope this answered your question.

      Thanks
      Paul

  • http://www.thetankhotel.com Samuel

    Hi Guys,
    I was wondering if it was at all possible for you to modify your plugin to be able to link to two different facebook pages on the one website, but different pages.

    For instance, I manage the online presence for http://www.thetankhotel.com, but within the venue itself is two very different bars. One is just an average Australian pub, the other is a very unique Craft Beer Bar. The Owners of the venue want it all to be one website, but two Facebook pages.

    In this essence, I would love to have the corresponding facebook feed in the side bar of page on the website. Is it at all possible?

    https://www.facebook.com/thetankhotel
    https://www.facebook.com/underbelly.tankhotel

    Any help would be amazing!

  • Pingback: How To: Create A Facebook Like Box – EviePost

  • Mikkel

    Is it possible to style the like box? I remember I’ve read somewhere that you could ad a css parameter to the code and have it point to a custom stylesheet and use this to get complete control over the styling?

  • http://newstylenet.com/ Tarun

    Thanx , It really helped me
    now I have a Facebook like box

  • http://bowesales.com Jesse

    Hi Paul,

    I really enjoyed this tutorial and your plugin is amazing. I actually complimented it on a blog post I recently wrote on my own site. Wondering though, is it at all possible to make the box flexible for responsive sites. I’ve tried a couple of things to get it to work but just can’t wrap my head around it. I’m sure it’s a simple solution too. Ideally having a fixed width is great to match the width of the sidebar but when we need to view it on a tablet or smaller device it needs to have a flexible width to accommodate for screen size.

    Any ideas?

    Thanks again for this tutorial and plugin.

    • http://bowesales.com Jesse

      I may have a solution for this and if I’ve butchered your plugin by doing this, I apologize…

      After your add_js() function I added this:

      
      public function add_css(){
      		echo '<style type="text/css">
      		
      		.fb_iframe_widget {
      		background: #f2f2f2;
      		width: 100% !important;	
      		}
      		.fb_iframe_widget span, .fb_iframe_widget iframe { width: 100% !important; }
      		
      		</style>'; 
      	}
      
      

      It kills the width functionality you added to the widget but it makes it flexible for responsive themes.

  • Kara

    Is it possible to wrap the text around the profile image?

  • http://lukplaz.com/ Lukplaz

    thank you for this plugin.

  • JamesZimbardi

    Hey Paul, Love the plugin! For some reason I lost the white background and the widget is now transparent. I did not make any changes to the widget. See: http://www.orlandomusicinstitute.com. Can you help me resolve this issue? Thanks!

  • http://www.facebook.com/caleb.wright.802 Caleb Wright

    Hey Paul, I would also like a fix for the transparent background. Can you please put out an update that lets us control the background color, or at least get a white option?

  • Pankaj

    Thankss for sharing this lovely plugin…Now i too can have the Facebook like a box…

  • http://www.gojak.in.rs/ Gojak

    HI, where is the license for this plugin? Can it be included in free and commercial WP themes? Thanks.