How To Create A Google Plus Badge WordPress Widget


Google+ is now the third biggest social network behind Facebook and Twitter, this means more and more people are starting to use the network more.

If you are using Google+ then you want to addvertise that you are on Google+.

Google have already thought of this and created a page where you can easily create your own Google plus badge.

Create Your Google Plus Badge

With this tool you can create 3 types of badges the icon, the small badge and the large badge.

Google Badge Icon

Google Small Badge

Google Large Badge


But if you choose the icon you have further options of small, medium and large sized icons. If you choose large or small badge you then have further choices of width and theme. With all these different options you could be making a couple of changes before it suits the theme of the blog.

For this reason we are going to create this same tool in WordPress as a WordPress Widget, having this as a Widget mean that we can quickly edit the badge to suit our theme.

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 a 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 Widget 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 it's functions.

There are 3 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 Google Badge Widget

Now we understand how to create a WordPress widget we can look into what we want this WordPress widget to do.

We want it to duplicate the same functionality you can get from the Google plus badge page.

Create Your Google Plus Badge

To achieve this we want the widget to have six options.

  • Widget Title
  • Google Profile ID
  • Badge Width
  • Badge Type
  • Google Theme
  • Profile Type

The combination of the above setting will allow us to create a Google Badge to achieve exactly what we want.

The benefit of having this as a WordPress widget is that you can easily add it to any Sidebar on your theme. You will easily be able change the badge when it's on your theme.

To create the different badges we need to use the Google plus html tag with the following attributes.

  • Href - The URL of the Google profile
  • Rel - The type of profile publisher or author
  • Width - The badge width
  • Height - The badge height
  • Theme - The Google theme ligt or dark
<g:plus href="https://plus.google.com/110725720433094046987" rel="publisher" width="300" height="131" theme="light"></g:plus>

Defining The Plugin

First we need to start off by defining the WordPress plugin, this is done by adding the following comments to the top of your php file.

/*
 * Plugin Name: Paulund Google Badge Widget
 * Plugin URI: http://www.paulund.co.uk
 * Description: A widget that allows you to display Your Google Plus badge
 * 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. 
*/

Registering The Widget

When the plugin is activated on your WordPress plugin it will run the rest of the PHP code in your plugin, we are going to create a widget. For WordPress to use the widget you need to register it so WordPress understands that this plugin is only going to be used for a Widget.

To register the WordPress widget use the following code.

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

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

}

Google Widget Constructor

Below is the Google badge Widget constructor this will run when the widget is registered we need to define the widget base ID, name of the widget and the description of the Widget.

/**
	 * Register widget with WordPress.
	 */
	public function __construct() {
		
		parent::__construct(
			'pu_google_badge_widget',		// Base ID
			'Google Plus Badge Widget',		// Name
			array(
				'classname'		=>	'pu_google_badge_widget',
				'description'	=>	__('A widget that allows you to display your Google Plus badge.', 'framework')
			)
		);

	} // end constructor

Widget Function

The widget function is used to display the Google badge within the WordPress sidebar, from this widget we get the values of the data stored in the database and create the Google badge from this data.

You will notice in this function we add an action to the footer of WordPress, on this action we will run the function add_js().

The add_js function will echo the required javascript to display a Google badge, in this Javascript we need display the Google profile ID and the profile type.

When we display the Google badge we need to know which type of badge to display, so we use the variable google_badge_type to decide if we display the Google icon or Google badge.

/**
 * 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->google_title = apply_filters('widget_title', $instance['title'] );
		
	$this->google_profile_id = $instance['profile_id'];
	$this->google_width = $instance['width'];
	$this->google_badge_type = $instance['badge_type'];
	$this->google_theme = $instance['theme'];
	$this->google_profile_type = $instance['profile_type'];
		
	add_action('wp_footer', array(&$this,'add_js'));

	/* Before widget (defined by themes). */
	echo $before_widget;

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

	/* Display Google Badge */
	if($this->google_badge_type == "Icon"){
		?><a href="https://plus.google.com/<?php echo $this->google_profile_id; ?>?prsrc=3" style="text-decoration:none;"><img src="https://ssl.gstatic.com/images/icons/gplus-32.png" alt="" style="border:0;width:32px;height:32px;"/></a><?php
	} else {
		?>
            <g:plus href="https://plus.google.com/<?php echo $this->google_profile_id; ?>" 
            width="<?php echo $this->google_width; ?>" 
            height="<?php echo ($this->google_badge_type == "Small Badge" ? "69" : "131"); ?>" 
            theme="<?php echo $this->google_theme; ?>"></g:plus>
		<?php 
	}

	/* After widget (defined by themes). */
	echo $after_widget;
}

/**
 * Add Facebook javascripts
 */
public function add_js(){
	echo '<link href="https://plus.google.com/'.$this->google_profile_id.'" rel="'.$this->google_profile_type.'" /><script type="text/javascript">
		window.___gcfg = {lang: \'en\'};
		(function() 
		{var po = document.createElement("script");
		po.type = "text/javascript"; po.async = true;po.src = (\'https:\' == document.location.protocol ? \'https\' : \'http\') + "://apis.google.com/js/plusone.js";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(po, s);
		})();</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.

As for all the inputs we need to strip the tags we can just loop through the entire array and strip tags on the value to place in the new instance of the array.

/**
	 * 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 to remove HTML (important for text inputs)		
		foreach($new_instance as $k => $v){
			$instance[$k] = strip_tags($v);
		}

		return $instance;
	}

Form Function

Google_badge_widget

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->google_title,
		'profile_id' => $this->google_profile_id,
		'width' => $this->google_width,
		'badge_type' => $this->google_badge_type,
		'theme' => $this->google_theme,
		'profile_type' => $this->google_profile_type
		);
		
		$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>

		<!-- Profile id: Text Input -->
		<p>
			<label for="<?php echo $this->get_field_id( 'profile_id' ); ?>"><?php _e('Profile Id', 'framework') ?></label>
			<input type="text" class="widefat" id="<?php echo $this->get_field_id( 'profile_id' ); ?>" name="<?php echo $this->get_field_name( 'profile_id' ); ?>" value="<?php echo $instance['profile_id']; ?>" />
		</p>
		
		<!-- Badge 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>
		
		<!-- Badge Type: Select -->
		<p>
			<label for="<?php echo $this->get_field_id( 'badge_type' ); ?>"><?php _e('Badge Type', 'framework') ?></label>
			<select id="<?php echo $this->get_field_id( 'badge_type' ); ?>" name="<?php echo $this->get_field_name( 'badge_type' ); ?>">
				<option <?php echo ($instance['badge_type'] == "Icon" ? 'selected="selected"' : ''); ?>>Icon</option>
				<option <?php echo ($instance['badge_type'] == "Small Badge" ? 'selected="selected"' : ''); ?>>Small Badge</option>
				<option <?php echo ($instance['badge_type'] == "Large Badge" ? 'selected="selected"' : ''); ?>>Large Badge</option>
			</select>
		</p>
		
		<!-- Google Theme: Select -->
		<p>
			<label for="<?php echo $this->get_field_id( 'theme' ); ?>"><?php _e('Google Theme', 'framework') ?></label>
			<select id="<?php echo $this->get_field_id( 'theme' ); ?>" name="<?php echo $this->get_field_name( 'theme' ); ?>">
				<option <?php echo ($instance['theme'] == "Light" ? 'selected="selected"' : ''); ?>>Light</option>
				<option <?php echo ($instance['theme'] == "Dark" ? 'selected="selected"' : ''); ?>>Dark</option>
			</select>
		</p>
		
		<!-- Google Profile Type: Text Input -->
		<p>
			<label for="<?php echo $this->get_field_id( 'profile_type' ); ?>"><?php _e('Profile Type', 'framework') ?></label>
			<select id="<?php echo $this->get_field_id( 'profile_type' ); ?>" name="<?php echo $this->get_field_name( 'profile_type' ); ?>">
				<option <?php echo ($instance['profile_type'] == "Publisher" ? 'selected="selected"' : ''); ?>>Publisher</option>
				<option <?php echo ($instance['profile_type'] == "Author" ? 'selected="selected"' : ''); ?>>Author</option>
			</select>
		</p>
		
	<?php
	}

Download

That's all you need to create a WordPress plugin to create a widget to display your Google Badge in a WordPress sidebar. 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.

Download Google Plus Badge Widget

Advertise here 50% Off

Comment