Plugin Development

Create A Sharrre WordPress Plugin

A couple of months ago I wrote a tutorial about how you can use a jQuery plugin Sharrre to create your own custom share buttons for your website. This tutorial only stated how you can use this jQuery plugin on your website, as I also write a lot of WordPress tutorial a few people have asked how you can use this jQuery plugin in WordPress.

In this tutorial I will go through how you can build a WordPress plugin that uses the sharrre plugin, I will also make this plugin available on Github so anyone who wants to use or improve on this plugin can do so freely.

Sharrre - A plugin for sharing buttons

First Create A WordPress Plugin

To start off we first need to create the WordPress plugin to do this just create a new folder in the WordPress plugin folder and add a PHP file in the root of the plugin folder.

At the top of this PHP file we add the comments to let WordPress know that this is a plugin it can use.

/*
Plugin Name: Sharrre WordPress Plugin
Plugin URI: http://www.paulund.co.uk
Description: A WordPress plugin that will allow you to create your own share buttons using the jQuery Plugin Sharrre
Version: 1.0
Author: Paul Underwood
Author URI: http:/www.paulund.co.uk
*/

Even though in WordPress you don't need to know object oriented programming and can just use procedural functions in your plugins, I always prefer to work with objects and classes. So now the WordPress plugin is created we add our class to define the functionality of the sharrre button.

class Sharrre_Wordpress_plugin
{

}

This plugin will just display a sharrre button on the front-end of the site, at the moment there isn't any settings in the WordPress admin area, this means that we can instantiate the class when we are not in the admin area.

if(!is_admin())
{
	new Sharrre_Wordpress_Plugin();
}

Download Sharrre Plugin

The next step is to download the sharrre plugin which you can do on github.

Sharrre

Once you have downloaded this plugin we can now add this to our WordPress plugin, copy the sharrre folder into the plugin folder.

This will mean we have access to include the jQuery plugin on the page to display the sharrre button.

Back in the WordPress plugin we can make sure that the sharrre jQuery plugin is always included on the page by placing the wp_enqueue_script() function in the constructor of our plugin.

public function __construct()
{
	add_action( 'wp_enqueue_scripts', array(&$this, 'add_scripts') );
        add_action( 'wp_enqueue_style', array(&$this, 'add_styles') );
}

public function add_scripts()
{
	wp_enqueue_script( 'sharrre', plugins_url( 'sharrre/jquery.sharrre.min.js', __FILE__ ) , array('jquery') );
}

public function add_styles()
{
	wp_enqueue_style( 'sharrre-button-style', plugins_url( 'css/styling.css', __FILE__ ) );
}

The sharrre plugin will now be included on every page of our WordPress site but only on the front-end. We can now make the Javascript to display this button. Because we are using a WordPress plugin to output Javascript we need to be able to construct the options for the button on the server side. This means we need to create a method which will output the Javascript on the page, all we have to do is call this method where we want the sharrre button to appear.

Create a new method which we will use to output the Javascript.

/**
* Add the button to the page
*
* @param array  $buttons - Array of buttons you want to display
* @param String $div_id  - If the div id is null then we create a new div. If the div id is not null
*                          then we assume that a div has been created for the buttons
* @param String $url     - The url you want to share, if NULL then we get the current post URL
*/
public function add_button(array $buttons, $div_id = NULL, $url = NULL, $options = array())
{

}

This method has 4 parameters which will help us define the basic functionality of the sharrre plugin.

  • The first parameter is an array of buttons we want the sharrre plugin to display.
  • The second parameter is the ID we will use to identify the share button div. If this is NULL then the plugin will create a div for you. If you supply a div ID you need to make sure that this div exists on the page or the plugin will not create the sharrre buttons.
  • The third parameter is the URL we will share from the button. If this parameter is NULL the plugin will use the current post URL, by using the function get_permalink().
  • The sharrre plugin allows you to customise the display of the buttons you can activate them on hover, display a counter or track the click events. Here are the options you have available in this array.
    • enableHover - Default is true.
    • enableCounter - Default is true.
    • enableTracking - Default is false.

From these parameters we will have all the information we need to output a sharrre button.

/**
 * Add the button to the page
 *
 * @param array  $buttons - Array of buttons you want to display
 * @param String $div_id  - If the div id is null then we create a new div. If the div id is not null
 *                          then we assume that a div has been created for the buttons
 * @param String $url     - The url you want to share, if NULL then we get the current post URL
 */
public function add_button(array $buttons, $div_id = NULL, $url = NULL, $options = array())
{
    $optionsDefaults = array('enableHover' => true, 'enableCounter' => true, 'enableTracking' => false);

    $buttonOptions = wp_parse_args( $options, $optionsDefaults );

    if(is_null($url))
    {
        $currentPostUrl = get_permalink();

        if(!empty($currentPostUrl))
        {
            $url = $currentPostUrl;
        }
    }

    if(is_null($div_id))
    {
        $div_id = 'sharrre_button';
        printf('<div id="%s"></div>', $div_id);
    }
    ?>
            <div id="<?php echo $id; ?>"></div>
		<script>
			jQuery('#<?php echo $id; ?>').sharrre({

			<?php
				if(!empty($buttons))
				{
					echo 'share: {';

					foreach($buttons as $button)
					{
						echo $button . ': true,';
					}

					echo '},';
				}

                                if(!$buttonOptions['enableHover'])
                                {
                                    echo 'enableHover: false,';
                                }

                                if(!$buttonOptions['enableCounter'])
                                {
                                     echo 'enableCounter: false,';
                                }

                                if($buttonOptions['enableTracking'])
                                {
                                    echo 'enableTracking: true,';
                                }

				if($url != '')
				{
					printf("url: '%s',", $url);
				}
			?>
			});
		</script>
	<?php
}
[/php]

We can now call this function on the front-end for the sharrre buttons to be displayed. When this plugin is activated it will automatically include this on the page, so we have access to the <strong>Sharrre_Wordpress_Plugin</strong> object.

In your theme files find the place you want to display the share button and add the following code.

[php]
<?php
    $share = new Sharrre_Wordpress_Plugin();
    $share->add_button(array('twitter', 'googlePlus', 'facebook'), 'div_id', get_permalink());
?>
<div id="div_id"></div>

This will create a basic button with no styling and when you hover over the link it will display the Twitter button, Google plus button and Facebook button. To style this button like the share button in the previous tutorial you can now add the CSS to the plugin CSS file which we will include on the page at the same time as we load the plugin.

sharrre4

I've made this plugin available with the above code on Github, which you can download here.

Sharrre WordPress Plugin

Additional Functionality

This is a very basic overview of the sharrre plugin, this just demonstrates a way of using WordPress with this jQuery plugin. There is a lot more functionality that we can include with the sharrre button here is a list of additional options you can pass into the sharrre plugin.

  • className - Define the class name to add
  • share - Define which social networks to use.
  • template - Define your own HTML to be rendered.
  • url - URL to be shared
  • text - Text to be used with the sharing buttons
  • urlCurl - Use your own PHP script to get the count of shares.
  • count - To count the amount of shares
  • total - Total number of shares
  • shorterTotal - A boolean value to shorten the number of total shares to 1.2M format.
  • enableHover - A boolean value to allow hover on sharing buttons
  • enableCounter - A boolean value to disable the counter.
  • enableTracking - A boolean value to enable Google analytic tracking.
  • hover - Define function to run on hover
  • hide - Define a function for hide event
  • click - Define a function for click event
  • render - Define a function for render event
  • buttons - Define behaviour for social buttons.
    googlePlus : {  //http://www.google.com/webmasters/+1/button/
      url: '',  //if you need to personnalize button url
      size: 'medium',
      lang: 'en-US',
      annotation: ''
    },
    facebook: { //http://developers.facebook.com/docs/reference/plugins/like/
      url: '',  //if you need to personalize url button
      action: 'like',
      layout: 'button_count',
      width: '',
      send: 'false',
      faces: 'false',
      colorscheme: '',
      font: '',
      lang: 'en_US'
    },
    twitter: {  //http://twitter.com/about/resources/tweetbutton
      url: '',  //if you need to personalize url button
      count: 'horizontal',
      via: '',
      hashtags: '',
      related: '',
      lang: 'en'
    },
    digg: { //http://about.digg.com/downloads/button/smart
      url: '',  //if you need to personalize url button
      type: 'DiggCompact'
    },
    delicious: {
      url: '',  //if you need to personalize url button
      size: 'medium' //medium or tall
    },
    stumbleupon: {  //http://www.stumbleupon.com/badges/
      url: '',  //if you need to personalize url button
      layout: '1'
    },
    linkedin: {  //http://developer.linkedin.com/plugins/share-button
      url: '',  //if you need to personalize url button
      counter: ''
    },
    pinterest: { //http://pinterest.com/about/goodies/
      url: '',  //if you need to personalize url button
      media: '',
      description: '',
      layout: 'horizontal'
    }

If we want to add these button options to our plugin we can do so by adding a method for each button and define each of the properties for the button. This will allow us to fully customise how each of the social network buttons are displayed. For this we can pass in the options for the different buttons and convert them from an array into JSON.

public function google_plus_options( $options )
{
	$this->googlePlusOptions = json_encode($options);
}

public function facebook_button( $options )
{
	$this->facebookOptions = json_encode($options);
}

public function twitter_button( $options )
{
	$this->twitterOptions = json_encode($options);
}

public function digg_button( $options )
{
	$this->diggOptions = json_encode($options);
}

public function delicious_button( $options )
{
	$this->deliciousOptions = json_encode($options);
}

public function stumbleupon_button( $options )
{
	$this->stumbleuponOptions = json_encode($options);
}

public function linkedin_button( $options )
{
	$this->linkedinOptions = json_encode($options);
}

public function pinterest_button( $options )
{
	$this->pinterestOptions = json_encode($options);
}

Now we can use these in our add_button method to change the options on each of the social networks.

/**
 * Add the button to the page
 *
 * @param array  $buttons - Array of buttons you want to display
 * @param String $div_id  - If the div id is null then we create a new div. If the div id is not null
 *                          then we assume that a div has been created for the buttons
 * @param String $url     - The url you want to share, if NULL then we get the current post URL
 */
public function add_button(array $buttons, $div_id = NULL, $url = NULL, $options = array())
{
    $optionsDefaults = array('enableHover' => true, 'enableCounter' => true, 'enableTracking' => false);

    $buttonOptions = wp_parse_args( $options, $optionsDefaults );

    if(is_null($url))
    {
        $currentPostUrl = get_permalink();

        if(!empty($currentPostUrl))
        {
            $url = $currentPostUrl;
        }
    }

    if(is_null($div_id))
    {
        $div_id = 'sharrre_button';
        printf('<div id="%s"></div>', $div_id);
    }
    ?>
        <script>
            jQuery('#<?php echo $div_id; ?>').sharrre({

            <?php
                if(!empty($buttons))
                {
                    echo 'share: {';

                    foreach($buttons as $button)
                    {
                        echo $button . ': true,';
                    }

                    echo '},';
                }

                echo 'buttons: {';
                    if($this->googlePlusOptions)
                    {
                        echo 'googlePlus: ' . $this->googlePlusOptions . ',';
                    }
                    if($this->facebookOptions)
                    {
                        echo 'facebook: ' . $this->facebookOptions . ',';
                    }
                    if($this->twitterOptions)
                    {
                        echo 'twitter: ' . $this->twitterOptions . ',';
                    }
                    if($this->diggOptions)
                    {
                        echo 'digg: ' . $this->diggOptions . ',';
                    }
                    if($this->deliciousOptions)
                    {
                        echo 'delicious: ' . $this->deliciousOptions . ',';
                    }
                    if($this->stumbleuponOptions)
                    {
                        echo 'stumbleupon: ' . $this->stumbleuponOptions . ',';
                    }
                    if($this->linkedinOptions)
                    {
                        echo 'linkedin: ' . $this->linkedinOptions . ',';
                    }
                    if($this->pinterestOptions)
                    {
                        echo 'pinterest: ' . $this->pinterestOptions . ',';
                    }

                echo '},';

                if(!$buttonOptions['enableHover'])
                {
                    echo 'enableHover: false,';
                }

                if(!$buttonOptions['enableCounter'])
                {
                    echo 'enableCounter: false,';
                }

                if($buttonOptions['enableTracking'])
                {
                    echo 'enableTracking: true,';
                }

                if(!empty($url))
                {
                    printf("url: '%s',", $url);
                }
            ?>
            });
        </script>
    <?php
}
[/php]

When calling this object from the front-end we can now change the way the buttons are displayed by add the options before calling the method to display the buttons, by using the following code.

[php]
<?php
$share = new Sharrre_Wordpress_plugin();
$share->google_plus_options(array(
	'url' => 'http://www.google.com',
	'size' => 'Large',
	'lang' => 'en-US',
	'annotation' => ''
));

$share->twitter_button(array(
	'url' => 'http://www.twitter.com',
));

$share->add_button(array('twitter', 'googlePlus', 'facebook'), 'sharrre', home_url(), array('enableCounter' => false, 'enableHover' => false));
?>
<div id="sharrre"></div>

Now you can use this plugin to create your own share buttons for your WordPress site.

Contribute to this WordPress plugin on Github.

Sharrre WordPress Plugin

Back to top

Fastest WordPress Hosting With WPEngine

Stunning speed, powerful security, and best-in-class customer service. At WP Engine.

Risk free for 60 days