Advertisement
Widgets

Facebook Like Box Widget for WordPress

by

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

Related Posts
  • Code
    Theme Development
    Custom Controls in the Theme CustomizerTheme customizer custom control 400
    In the last article, we explored the advanced controls available in the Theme Customizer, and how to implement them. We’re going to look at how to create our own custom control, allowing you to choose which Category of Posts are displayed on the home page. To get started, download version 0.6.0 of our Theme Customizer Example.Read More…
  • Code
    Theme Development
    Creating a WordPress Theme from Static HTML - Adding WidgetsCreating wordpress theme from html 400
    In this series, you've learned how to convert a static HTML file to a WordPress theme and edit the header file. So far you've: prepared your markup for WordPress converted your HTML to PHP and split your file into template files edited the stylesheet and uploaded your theme to WordPress added a loop to your index file added meta tags, the wp_head hook and the site title and description to your header file added a navigation menu. Read More…
  • Code
    Plugins
    A Better Forum List Widget for bbPressBbpress
    When bbPress was still a standalone installation, I had tried it out and wasn't really impressed. Things were clunky and it didn't always work the way it was supposed to. After languishing for a few years, Automattic decided to take bbpress and turn it into a plugin, improving the functionality leaps and bounds and making it a strong contender amongst other forum option for WordPress.Read More…
  • Code
    Widgets
    Building a Countdown Timer WidgetBuilding a countdown timer widget preview
    We all love a celebration, and now that Easter is over, we look forward to the next occasion. How far away is the next occasion you like to celebrate? Whatever it might be, let's build a widget plugin to add a countdown timer to our sidebar showing how long we have left to wait.Read More…
  • Code
    Plugins
    Creating Client Testimonials With Custom Post TypesCreating client testimonials with custom post types
    If you're running any type of business online, it's a good idea to get your clients' opinions on what they thought about the services you provided. First of all, this can benefit you by giving you feedback on how you can improve aspects of your business, but most of all, it can give you great testimonials, which can help to persuade potential clients to use your services.Read More…
  • Code
    Widgets
    Twitter Trends Widget for WordPressPreview
    In this tutorial we are going to create a WordPress widget that displays Twitter Trends by region. We will use Twitter's Trends API and update trends after a specific time duration using WordPress' Transients API.Read More…