Skip to content

Kévin Dunglas

Founder of Les-Tilleuls.coop (worker-owned cooperative). Creator of API Platform, FrankenPHP, Mercure.rocks, Vulcain.rocks and of some Symfony components.

Menu
  • Talks
  • Resume
  • Sponsor me
  • Contact
Menu

Using SocialShare with WordPress to create custom social networks buttons

Posted on January 17, 2014February 14, 2014 by Kévin Dunglas

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!

Related posts:

  1. PHP SocialShare 0.2.1 released
  2. Introducing the SocialShare PHP library
  3. Plugin pour intégrer Scoopeo à votre blog WordPress
  4. Sécurisez votre blog WordPress !

4 thoughts on “Using SocialShare with WordPress to create custom social networks buttons”

  1. David says:
    January 17, 2014 at 2:50 pm

    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

    Reply
    1. Kévin Dunglas says:
      January 17, 2014 at 3:43 pm

      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.

      Reply
  2. wifesgeek says:
    March 18, 2014 at 10:01 pm

    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

    Reply
    1. Kévin Dunglas says:
      March 19, 2014 at 10:43 pm

      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

      Reply

Leave a ReplyCancel reply

Social

  • Bluesky
  • GitHub
  • LinkedIn
  • Mastodon
  • X
  • YouTube

Links

  • API Platform
  • FrankenPHP
  • Les-Tilleuls.coop
  • Mercure.rocks
  • Vulcain.rocks

Subscribe to this blog

Top Posts & Pages

  • JSON Columns and Doctrine DBAL 3 Upgrade
  • Securely Access Private Git Repositories and Composer Packages in Docker Builds
  • Preventing CORS Preflight Requests Using Content Negotiation
  • Symfony's New Native Docker Support (Symfony World)
  • FrankenPHP: The Modern Php App Server, written in Go
  • Develop Faster With FrankenPHP
  • How to debug Xdebug... or any other weird bug in PHP
  • PHP and Symfony Apps As Standalone Binaries
  • HTTP compression in PHP (new Symfony AssetMapper feature)
  • Generate a Symfony password hash from the command line

Tags

Apache API API Platform Buzz Caddy Docker Doctrine FrankenPHP Go Google GraphQL HTTP/2 Hydra hypermedia Hébergement Javascript JSON-LD Kubernetes La Coopérative des Tilleuls Les-Tilleuls.coop Lille Linux Mac Mercure Mercure.rocks Messagerie Instantanée MySQL performance PHP Punk Rock Python React REST Rock'n'Roll Schema.org Security SEO SEO Symfony Symfony Live Sécurité Ubuntu Web 2.0 webperf XML

Archives

Categories

  • DevOps (84)
    • Ubuntu (68)
  • Go (17)
  • JavaScript (46)
  • Mercure (7)
  • Opinions (91)
  • PHP (170)
    • API Platform (77)
    • FrankenPHP (9)
    • Laravel (1)
    • Symfony (97)
    • Wordpress (6)
  • Python (14)
  • Security (15)
  • SEO (25)
  • Talks (46)
© 2025 Kévin Dunglas | Powered by Minimalist Blog WordPress Theme