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.
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!
Bonjour Kevin,
It’s better and better, the third post about SocialShare will be for the WordPress plugin ? 😉
I will try this solution as soon as possible, and promote it as it sounds incredibly light in front of solutions like the JetPack’s one.
Great job 🙂
David
Thanks David.
And thanks to Morrison Laju to already have added support for two more social networks (LinkedIn and StumbleUppon).
Why not a WordPress plugin, but I’m not sure that this is necessary because this cannot be an “out of the box” solution. There is still need to write some CSS.
However, a Symfony 2 bundle is already planned.
Bonjour,
J’ai voulu mettre en place votre solution mais je n’ai pas très bien compris comment récupérer les librairies.
Pourriez-vous m’aider ?
Je vous remercie
Bonjour et merci pour l’intérêt que vous portez à ce projet.
Vous pouvez, au choix, utiliser Composer (https://getcomposer.org/) pour l’ajouter à votre projet ou télécharger un ZIP depuis cette page : https://github.com/dunglas/php-socialshare/releases