WordPressでプラグインを使わずにSNSボタンを設置するカスタマイズ!シェアカウント機能付きのイメージ

WordPressでプラグインを使わずにSNSボタンを設置するカスタマイズ!シェアカウント機能付き

  • WP

WordPressにはかんたんに機能を追加できるプラグインという仕組みが用意されています。

エンジニアとしての知識がなくても、豊富な機能をかんたんにサイトに導入出来るため、
WordPressを利用するうえでの大きな魅力のひとつです。

ただ、サイトの目的や必要な機能はそのサイトによって異なりますよね。

そのため、本来の意図よりも豊富な機能が搭載されていることで、
サイトの表示速度に影響を与えてしまうケースもあります。

今回はこういった背景をふまえてプラグインを極力使いたくないという方向けに、
必要最低限に絞ったSNSボタン(Twitter / Facebook / はてなブックマーク / Pocket)を
自作する方法をご紹介します。

目次

実際のコード

functions.php

こちらはTwitterとFacebookのカウント数を取得するための関数を用意しています。

/* Facebook Share Count
-----------------------------------------*/
if(!function_exists('get_fb_count')) {
  function get_fb_count($url, $cache){
    $cache = "fb-" . $cache;
    $res = get_transient( $cache );
    if ( $res === false ) {
      $access_token = "ここにFacebookのアクセストークンを入力";
      $encoded_url = rawurlencode( $url );
      $request_url = 'https://graph.facebook.com/?id='.$encoded_url.'&fields=engagement&access_token='.$access_token;
      $response = wp_remote_get( $request_url );
      $res = 0;
      if (!is_wp_error( $response ) && $response["response"]["code"] === 200) {
        $body = $response['body'];
        $json = json_decode( $body );
        $res = (isset($json->{'engagement'}->{'share_count'}) ? $json->{'engagement'}->{'share_count'} : 0);
      }
      $cache_time_hour = 3600 * 8;
      set_transient( $cache, $res, $cache_time_hour );
    } 
    return intval($res);
  }
}

/* Twitter Share Count(by count.jsoon)
-----------------------------------------*/
if(!function_exists('get_tw_count')) {
  function get_tw_count($url, $cache) {
    $cache = "tw-" . $cache;
    $res = get_transient( $cache );
    if ( $res === false ) {
      $encoded_url = rawurlencode( $url );
      $request_url = 'https://jsoon.digitiminimi.com/twitter/count.json?url=' . $encoded_url;
      $response = wp_remote_get( $request_url );
      $res = 0;
      if (!is_wp_error( $response ) && $response["response"]["code"] === 200) {
        $body = $response['body'];
        $json = json_decode( $body );
        $res = ($json->{"count"} ? $json->{"count"} : '0');
      }
      $cache_time_hour = 3600 * 8;
      set_transient( $cache, $res, $cache_time_hour );
    }
    return intval($res);
  }
}

なお、実際にカウント数を取得するためにはコードの実装だけではなく
後述する作業が別途必要となります。

single.phpへの実装

記事の詳細ページ(single.php)で実装する例でご紹介します。

なお、ボタンデザインはサンプルとしてFont Awesomeから取得する記述にしていますが、
画像に置き換えたりなどご自身のサイトにあわせて調整ください。

<div class="sns">
  <ul class="sns__list">
	<li class="sns__item">
		<?php $fb_count = get_fb_count(get_permalink(), get_the_ID()); ?>
		<a class="sns__link" href="https://www.facebook.com/plugins/like.php?href=<?php the_permalink(); ?>" onclick="javascript:window.open('https://www.facebook.com/plugins/like.php?href=<?php echo $url; ?>' ,null ,'width=650 ,height=450'); return false;" rel="nofollow">
			<span class="sns__count"><?php echo $fb_count; ?></span>
			<i class="fa fa-facebook-square" aria-hidden="true"></i>
		</a>
	</li>
	<li class="sns__item">
		<?php $tw_count = get_fb_count(get_permalink(), get_the_ID()); ?>
		<a class="sns__link" href="https://twitter.com/share?text=<?php the_title(); ?>&url=<?php the_permalink(); ?>&hashtags=<?php echo bloginfo('sitename'); ?>" onClick="window.open(encodeURI(decodeURI(this.href)), 'tweetwindow', 'width=650, height=470, personalbar=0, toolbar=0, scrollbars=1, sizable=1'); return false;" rel="nofollow">
			<span class="sns__count"><?php echo $tw_count; ?></span>
			<i class="fa fa-twitter-square" aria-hidden="true"></i>
		</a>
	</li>
	<li class="sns__item">
		<?php
			$bk_count = @file_get_contents( 'http://api.b.st-hatena.com/entry.count?url=' . rawurlencode( get_permalink() ) );
			if( !isset( $bk_count ) || empty( $bk_count ) )
			{
				$bk_count = 0;
			}
		?>
		<a class="sns__link" href="https://b.hatena.ne.jp/entry/<?php the_permalink(); ?>" data-hatena-bookmark-layout="simple" title="このエントリーをはてなブックマークに追加">
			<span class="sns__count"><?php echo $bk_count; ?></span>
			<span class="sns__hatena">B!</span>
		</a>
	</li>
	<li class="sns__item">
		<?php 
			$query = 'https://widgets.getpocket.com/api/saves?url=' . rawurlencode(get_permalink());
			$json = @file_get_contents( $query );
			$pk_count = json_decode($json, true);
		?>
		<a class="sns__link" href="https://getpocket.com/edit?url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" rel="nofollow" target="_blank">
			<span class="sns__count" id="js-pk"><?php echo $pk_count["saves"]; ?></span>
			<i class="fa fa-get-pocket" aria-hidden="true"></i>
		</a>
	</li>
  </ul>

style.cssで見た目を調整

CSSはかんたんなサンプルです。
ご自身のサイトデザインに合わせて自由にカスタマイズいただければ幸いです。

.sns__list {
  display: flex;
  justify-content: flex-start;
}
.sns__item {
  margin: 0 10px;
}
.sns__link {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

Facebookのシェア数(いいね)取得について

現在のFacebookのAPI仕様では、シェア数(いいね)を取得するにあたり、
以下手順でアクセストークンを準備する必要があります。

  • Facebook for Developersを開く
  • マイアプリからアプリの作成を選ぶ
  • 表示名(任意の名前)とメールアドレスを入力
  • アプリIDを作成してくださいをクリック
  • ダッシュボードが表示したら画面左の設定からベーシックへ進む
  • サンプルURLを開きURLの「APPID」と「APPSECRET」の部分をご自身のアプリIDとapp secretへ置き換えて開き直す
  • 表示したページ内のaccess_tokenがアクセストークンとなる
  • functions.php$access_tokenにアクセストークンを入力する
  • これでシェア数が取得できるようになる

Twitterのシェア数取得

Twitterは公式のAPIでカウント数を取得することができなくなりました。 そのため外部サイトを利用した例をご紹介します。

  • widgetoon.js & count.jsoonを開く
  • サイト登録申請を行う
  • サイトのURL、メールアドレスを登録する
  • 数日後、登録完了のメールが届く
  • widgetoon.js & count.jsoonにアクセスしTwiiter連携を行う
  • これでシェア数が取得できるようになる

実装についての補足と解説

TwitterとFacebookについてはAPIからカウント数を取得するための処理を
functions.php内の関数で処理しています。

また、アクセス数が多くなるとAPI制限にかかる可能性があるため、
毎回値をAPIから取得するのではなく、Transients APIのキャッシュを
利用するようにしています。

最後に

サイトの高速化はユーザー体験やSEOに影響を与える要素になります。
プラグインが悪いということではなく、あくまでも選択肢のひとつとして
利用しない方法をご紹介いたしました。

ご自身の目的にあわせて選定する際の一助になれば幸いです。

  1. SNIPPET
  2. WordPress
  3. WordPressでプラグインを使わずにSNSボタンを設置するカスタマイズ!シェアカウント機能付き