PHP SocialShare 0.2.1 released

I’ve just published a new version of PHP SocialShare, a library allowing to retrieve server-side webpages’ number of shares and share link from social networks.

This release fixes a bug that was breaking the Google support when the number of shares if greater than 1K and use the brand new phpspec 2.0 stable release as spec system.

PHP SocialShare is available on GitHub and installable trough the awesome Composer.

The SocialShare library

Using SocialShare with WordPress to create custom social networks buttons

2013/02/14: Take care of the smarter caching system introduced in version 0.2.0.

Here is how to use the SocialShare PHP library to create custom Facebook, Twitter and Google Plus share buttons including the number of share.

The SocialShare library

Installing the library

The first step is to install SocialShare through the awesome Composer dependency manager. If you have not installed composer already, grab it!

In your custom WordPress themes directory (something like wp-content/themes/<mytheme-name>/), run the following command to get a copy of the library:

php /path/to/composer.phar require dunglas/php-socialshare:~0.1

Two Composer related files are created: composer.json and composer.lock. They contain the list dependencies of our project (only SocialShare for now). The code of SocialShare and Doctrine Cache (a dependecy of SocialShare) have been downloaded in the vendor/ directory.

Initializing SocialShare and creating helper functions

Put the following code in your theme’s functions.php file:

// Social share initialization

use Doctrine\Common\Cache\PhpFileCache;
use SocialShare\SocialShare;
use SocialShare\Provider\Facebook;
use SocialShare\Provider\Twitter;
use SocialShare\Provider\Google;

require 'vendor/autoload.php';

$cache = new PhpFileCache('/a/cache/directory'); // Use sys_get_temp_dir() to get the system temporary directory, but be aware of the security risk if your website is hosted on a shared server
$socialShare = new SocialShare($cache);

$socialShare->registerProvider(new Facebook());
$socialShare->registerProvider(new Twitter());
$socialShare->registerProvider(new Google());

function social_share_link($providerName, $url, $options = array())
{
    global $socialShare;

    return $socialShare->getLink($providerName, $url, $options);
}

function social_share_shares($providerName, $url)
{
    global $socialShare;

    return $socialShare->getShares($providerName, $url, true);
}

add_action('shutdown', array($socialShare, 'update'), 10000);

if (function_exists('fastcgi_finish_request')) {
    add_action('shutdown', 'fastcgi_finish_request', 1);
}

It loads the library through the Composer autoloading system, initializes a file based cache system (be sure to set a directory writable by your web server)  and loads Facebook, Twitter and Google Plus providers.

If you want to use other social networks such as Pinterest (bundled with SocialShare) or the newly supported LinkedIn, register them here.

Then, we create two helper functions to use in our theme’s templates: social_share_links that returns a share link and social_share_shares that returns the share counter. The last parameter of \SocialShare\SocialShare::getShares() function is set to true. This allows to delay the retrieving of share counts from social network when the \SocialShare\SocialShare::update() method will be called. If a value is already in the cache (how old it is doesn’t matter) it will be used, otherwise 0 will be returned.

Finally, we register the call to the update method on the WordPress’ shutdown hook. Thanks to this tweak, HTTP requests retrieving shares counts from social networks will be issued after the page load. Of course, only the next visitor will see updated counts, but this allows fast pages loading even in the worst case: when the data must be updated from social networks servers.

A last trick: if WordPress is served through PHP FPM (the most performant solution for PHP websites), we take care of the fastcgi_finish_request method. This method (only available when using PHP FPM) allows flushing the buffer and closing the connection to the client before retrieving data from social networks. By default, WordPress flush the response buffer but does not close the connection, even on FPM.

I’ve submitted a patch upstream using this trick to increase performance of all WordPress installations on PHP FPM, so I hope that the last lines of code will become unnecessary soon!

Using the helpers

You can now use the registered helpers in any template. Here is an example to put inside The WordPress Loop (e.g. content.php) to display a link to share the post and it’s number of share on Twitter, Facebook and Google Plus:

        <ul class="entry-social">
            <li><a href="<?php echo social_share_link('facebook', get_permalink()) ?>" rel="nofollow" class="facebook-share"><span class="facebook">Facebook</span> <span class="number"><?php echo social_share_shares('facebook', get_permalink()) ?></span></a></li>
            <li><a href="<?php echo social_share_link('twitter', get_permalink(), array('text' => html_entity_decode(get_the_title()), 'via' => 'dunglas')) ?>" class="twitter-share" rel="nofollow"><span class="twitter">Twitter</span> <span class="number"><?php echo social_share_shares('twitter', get_permalink()) ?></span></a></li>
            <li><a href="<?php echo social_share_link('google', get_permalink()) ?>" class="google-share"><span class="google-plus">Google Plus</span> <span class="number"><?php echo social_share_shares('google', get_permalink()) ?></span></a></li>
        </ul>

Customize the apparence of your social buttons with all the CSS you want!