Create A Multi Author About Me WordPress Widget

It's common in many blogs to have an about me widget in the sidebar of the blog which displays the biography of the author. This is a great place to show everyone your name, your biography, your picture and your social media links. If you want to do this in WordPress you can add a standard text widget and input this information manually.

But the problem comes if you have multiple authors on your WordPress blog, if you add a text widget then this will be displayed the same way on every page. The solution to this is to create a WordPress widget that will only show the author of the current page in the Widget.

In this tutorial we are going to create a WordPress widget that will display the author of the current post and will use the in-built WordPress user manager to store all the information we need.

Create A WordPress Widget

multi-author-about-me-widget
To start with we need to register a WordPress widget, this is as easy as creating a WordPress plugin. All you have to do is create a new folder in the wp-content/plugins directory for your plugin and make a new php file inside this folder.

In the new PHP file add the following comments to your code.

/*
 * Plugin Name: Multi Author About Me Widget
 * Plugin URI: [Your Website]
 * Description: A widget that allows you to display either a specific author for your site, or current posts author.
 * Version: 1.0
 * Author: [Author Name]
 * Author URI: [Author URL]
 * 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.
*/

The best way to create a widget in WordPress is to inherit from the WP_Widget class and override the functions widget(), update() and form(). You can see how you will create this by viewing the WordPress Widget Boilerplate.

First we need to register this new Widget on WordPress so that it will appear on the widget dashboard, to do this and see your new widget add the following code.

<?php
add_action( 'widgets_init', create_function( '', 'register_widget("paulund_multi_author_about_me_widget");' ) );

class paulund_multi_author_about_me_widget extends WP_Widget
{
	/**
	 * Register widget with WordPress.
	 */
	public function __construct() {

		parent::__construct(
			'multi_author_about_me_widget',				// Base ID
			'Multi Author About Me Widget',		// Name
			array(
				'classname'		=>	'multi_author_about_me_widget',
				'description'	=>	__('A widget that allows you to display either a specific author for your site, a list of all authors, or current posts author.', 'framework')
			)
		);

	} // end constructor

	/**
	 * 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 ) {

	}

	/**
	 * 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 ) {

	}

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

 	}
}
?>

You will now see this new widget on the widget dashboard, but it won't do anything as we need to complete the rest of the widget.

Widget Constructor

In the widget constructor we need to do a couple of things to setup the widget, first we need to add additional social profiles to the WordPress user manager, then we are going to include a colour picker on the admin screen so that the user can choose how to style the background and font colours.

/**
 * Register widget with WordPress.
 */
public function __construct() {
	add_filter( 'user_contactmethods', array(&$this, 'add_social_media_networks'), 10, 1);
	add_action( 'admin_enqueue_scripts', array(&$this, 'enqueue_styles') );

	parent::__construct(
		'multi_author_about_me_widget',				// Base ID
		'Multi Author About Me Widget',		// Name
		array(
			'classname'		=>	'multi_author_about_me_widget',
			'description'	=>	__('A widget that allows you to display either a specific author for your site or current posts author.', 'framework')
		)
	);
} // end constructor

The first line of this constructor will use the filter user_contactmethods, which will allow us to use add additional fields to the user manager, this filter will call the following function.

public function add_social_media_networks()
{
	$contactmethods['rss_url'] = 'RSS URL';
	$contactmethods['google_profile'] = 'Google Username';
	$contactmethods['twitter_profile'] = 'Twitter Username';
	$contactmethods['facebook_profile'] = 'Facebook Username';
	$contactmethods['pinterest_profile'] = 'Pinterest Username';
	$contactmethods['flickr_profile'] = 'Flickr Username';
	$contactmethods['youtube_profile'] = 'YouTube Username';
	$contactmethods['skype_profile'] = 'Skype Username';
	$contactmethods['digg_profile'] = 'Digg Username';

	return $contactmethods;
}

The second line of the constructor function will include Javascript and Stylesheets for the colour pickers on the WordPress Widget page, this will call the following function. This function will use the built in WordPress colour picker which is called farbtastic, the way you include this on the page is simply by using the functions wp_enqueue_style() and wp_enqueue_script().

public function enqueue_styles()
{
	wp_enqueue_style('farbtastic');
	wp_enqueue_script('farbtastic');
}

Creating The Widget Form

When you add the widget to a sidebar on the WordPress dashboard you can add a form to customise the look and feel of the widget. For this widget we need to add a number of different options to customise this correctly, we will need to have the following options.

  • Select a user from a dropdown.
  • Enter the size of your avatar.
  • A checkbox to always display the current author.
  • The background colour picker
  • The font colour picker
  • The social media icons

All these settings need to be defined inside the form function for this to be displayed on the widget dashboard screen.

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

// Set up some default widget settings
$defaults = array(
	'display_author' => '',
	'override' => '1',
	'background' => '#ffffff',
	'font_color' => '#000000',
	'avatar_size' => '125',
	'icon_color' => 'black'
);

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

<p>
	<label for="<?php echo $this->get_field_id( 'display_author' ); ?>"><?php _e('Display Author:', 'framework') ?></label>
	<?php wp_dropdown_users( array('id' => $this->get_field_id( 'display_author' ),
									'name' => $this->get_field_name( 'display_author' ),
									'selected' => $instance['display_author']
									) ); ?>
</p>

<p>
	<label for="<?php echo $this->get_field_id( 'avatar_size' ); ?>"><?php _e('Avatar Size:', 'framework') ?></label>
	<input type="text" name="<?php echo $this->get_field_name( 'avatar_size' ); ?>" id="<?php echo $this->get_field_id( 'avatar_size' ); ?>" value="<?php echo $instance['avatar_size']; ?>" />
</p>

<p>
	<label for="<?php echo $this->get_field_id( 'override' ); ?>"><?php _e('Override Author With Current Post Author:', 'framework') ?></label>
	<input type="checkbox" name="<?php echo $this->get_field_name( 'override' ); ?>" id="<?php echo $this->get_field_id( 'override' ); ?>" <?php checked( $instance['override'], '1', true ); ?> value="1" />
</p>

	<script type="text/javascript">
		//<![CDATA[
			jQuery(document).ready(function()
			{
				jQuery('.widefat').focus(function(){
					var $this = jQuery(this);
					$this.parent().next().show();
				}).focusout(function(){
					var $this = jQuery(this);
					$this.parent().next().hide();
				});
				jQuery('.widget-color-picker').hide();
				// colorpicker field
				jQuery('.widget-color-picker').each(function(){
					var $this = jQuery(this),
						id = $this.attr('rel');
						$this.farbtastic('#' + id);
				});

			});
		//]]>
	</script>

 <p>
       	<label for="<?php echo $this->get_field_id('background'); ?>"><?php _e('Background Color:', 'framework'); ?></label>
       	<input class="widefat" id="<?php echo $this->get_field_id('background'); ?>" name="<?php echo $this->get_field_name('background'); ?>" type="text" value="<?php echo $instance['background']; ?>" />
	<div class="widget-color-picker" rel="<?php echo $this->get_field_id('background'); ?>"></div>
</p>

<p>
       	<label for="<?php echo $this->get_field_id('font_color'); ?>"><?php _e('Font Color:', 'framework'); ?></label>
       	<input class="widefat" id="<?php echo $this->get_field_id('font_color'); ?>" name="<?php echo $this->get_field_name('font_color'); ?>" type="text" value="<?php echo $instance['font_color']; ?>" />
	<div class="widget-color-picker" rel="<?php echo $this->get_field_id('font_color'); ?>"></div>
</p>

<p>
       	<label for="<?php echo $this->get_field_id('icon_color'); ?>"><?php _e('Icon Color:', 'framework'); ?></label>
       	<select id="<?php echo $this->get_field_id('icon_color'); ?>" name="<?php echo $this->get_field_name('icon_color'); ?>">
       		<option value="black">Black</option>
       		<option value="blue">Blue</option>
       		<option value="limegreen">Lime Green</option>
       		<option value="orange">Orange</option>
       		<option value="pink">Pink</option>
       		<option value="purple">Purple</option>
       		<option value="red">Red</option>
       	</select>
</p>

<?php
}

Saving The Form Data

On saving of the widget data the widget will automatically call the function update(), so inside this function we will do any validation that needs to be done to the values.

There are two parameters that are passed into the update function the first parameter are the new values which coming from the form, the second parameter are the old values which are already stored in the database. The return of this function will be that values which are going to be stored on 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.
 */
public 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);
	}

	$instance['display_author'] = $new_instance['display_author'];
	$instance['override'] = (bool)$new_instance['override'];

	return $instance;
}

Displaying The Widget On Your Site

When you move the widget into a sidebar area, change the settings and click save on these settings the widget will be stored in this sidebar and will be displayed on your site.

When the widget is going to be displayed in a sidebar it will use the function widget() and passes in two parameters, the first parameter will define the arguments of the widget. The second parameter will be all the settings you have stored in the widget form, we need to use both of these in the widget function.

On the form for the widget we allowed the user to choose a specific user to display or allow them to override this user and display the current author of the post.

To get all the user information we need we need to use the functions get_userdata() and get_user_meta() and pass in the user ID to get the data for this certain user.

if((int)$override === 1 && is_single())
{
	$display_author = get_the_author_meta('ID');
}

$user_info = get_userdata( $display_author );
$user_meta = get_user_meta( $display_author );

Now we can use this data to display the information on the about me widget. Below is the rest of the code we need to display the author name, author bio, author avatar and social icons.

/**
 * 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 );
	extract( $instance );

	if((int)$override === 1 && is_single())
	{
		$display_author = get_the_author_meta('ID');
	}

	$user_info = get_userdata( $display_author );
	$user_meta = get_user_meta( $display_author );

	// Our variables from the widget settings
	$title = '';

	// Before widget (defined by theme functions file)
	echo $before_widget;

	// Display the widget title if one was input
	if ( $title )
		echo $before_title . $title . $after_title;
	?>

	<div id="about_me_widget" <?php echo 'style="background-color:'. $background.'; color:'.$font_color.'"'; ?>>
		<h2><?php  echo $user_info->display_name; ?></h2>
		<p><?php  echo get_avatar( $user_info->user_email, $avatar_size ); ?></p>
		<p><?php  echo $user_meta['description'][0]; ?></p>

		<div class="about_me_widget_social_icons">
			<?php
				$url = trailingslashit( plugins_url( 'img', __FILE__ ) );

				if(isset($user_meta['rss_url']) && $user_meta['rss_url'][0] != '')
				{
					?><a href="<?php echo $user_meta['rss_url'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Subscribe To RSS" /></a><?php
				}

				if(isset($user_meta['google_profile']) && $user_meta['google_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['google_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Circle On Google Plus" /></a><?php
				}

				if(isset($user_meta['twitter_profile']) && $user_meta['twitter_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['twitter_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Follow On Twitter" /></a><?php
				}

				if(isset($user_meta['facebook_profile']) && $user_meta['facebook_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['facebook_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Like On Facebook" /></a><?php
				}

				if(isset($user_meta['pinterest_profile']) && $user_meta['pinterest_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['pinterest_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Follow On Pinterest" /></a><?php
				}

				if(isset($user_meta['flickr_profile']) && $user_meta['flickr_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['flickr_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Follow On Flickr" /></a><?php
				}

				if(isset($user_meta['youtube_profile']) && $user_meta['youtube_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['youtube_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Subscribe To YouTube" /></a><?php
				}

				if(isset($user_meta['skype_profile']) && $user_meta['skype_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['skype_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Talk On Skype" /></a><?php
				}

				if(isset($user_meta['digg_profile']) && $user_meta['digg_profile'][0] != '')
				{
					?><a href="<?php echo $user_meta['digg_profile'][0]; ?>"><img src="<?php echo $url . $icon_color . '-01.png'; ?>" alt="" title="Follow On Digg" /></a><?php
				}
			?>
		</div>

	</div>

	<?php

	// After widget (defined by theme functions file)
	echo $after_widget;
}

If you now visit your site you will see the multi author about me widget in the sidebar of your blog. If you are not on a single post then the default user will be displayed, when you click on a post from a different author the widget will change to display the information of the author of the current post.

In this code there are images that will display your social media icons, there are options to have different style of social media buttons. I haven't included them in this tutorial so you can use your favourite icons for the social networks.

Advertise here 50% Off

Comment