WordPressでプラグインをつかわずにSNSボタンを設置する方法
今回はWordPressにSNSのシェアボタンを設置する方法を紹介します。プラグインは使いません。
プラグインを使えば様々なSNSに対応することも簡単に出来ますが、現実的にはtwitter、facebook、はてブ、pocketくらいで充分かと思います。海外向けに記事を書いている場合は他のSNSを設置する必要があるのかも知れませんが。僕みたいに日本の方に読んでもらおうとしているのであれば、先の4つくらいで事足ります。
実装方法
single.php
single.phpに下記を記述します。ここではtwitter、facebook、はてブ、pocketのシェアボタンを設置するとします。以前であればGoogle+も設置していましたが、サービスが終了したのでもういらないですね。
<?php
$url_encode=urlencode(get_permalink());
$title_encode=urlencode(get_the_title()).'|'.get_bloginfo('name');
?>
<ul>
<li><a href="//twitter.com/intent/tweet?url=<?php echo $url_encode ?>&text=<?php echo $title_encode ?>&tw_p=tweetbutton" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;">twitter</a></li>
<li><a href="//www.facebook.com/sharer.php?src=bm&u=<?php echo $url_encode;?>&t=<?php echo $title_encode;?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;">facebook</a></li>
<li><a href="//b.hatena.ne.jp/entry/<?php echo $url_encode ?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=510');return false;">hatena</a></li>
<li><a href="https://getpocket.com/edit?url=<?php echo $url_encode;?>&t=<?php echo $title_encode;?>" target="_blank" rel="nofollow">pocket</a></li>
</ul>
説明
記事とサイト情報の取得・出力
記事タイトルとサイト名の取得は下記のソースで行っています。
<?php
$url_encode=urlencode(get_permalink());
$title_encode=urlencode(get_the_title()).'|'.get_bloginfo('name');
?>
出力は下記の通りです。
<?php echo $url_encode;?>&t=<?php echo $title_encode;?>
各SNSボタン
<a href="//twitter.com/intent/tweet?url=<?php echo $url_encode ?>&text=<?php echo $title_encode ?>&tw_p=tweetbutton" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;">twitter</a>
<a href="//www.facebook.com/sharer.php?src=bm&u=<?php echo $url_encode;?>&t=<?php echo $title_encode;?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;">facebook</a>
はてブ
<a href="//b.hatena.ne.jp/entry/<?php echo $url_encode ?>" onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=510');return false;">hatena</a>
<a href="https://getpocket.com/edit?url=<?php echo $url_encode;?>&t=<?php echo $title_encode;?>" target="_blank" rel="nofollow">pocket</a>
ボタンにアイコンをつかう場合
テキストだけのボタンではなく、それぞれのサービスのアイコンも使いたい場合ですが、twitter、facebook、pocketはFontAwesomeにあるので簡単に導入できます。FontAwesomeについては下記でも触れています。
問題ははてブ。こちらは日本だけのサービスなのでどうしても海外サイトであるFontAwesomeには素材がありません。僕はいつも下記サイトでsvgをダウンロードして使わせてもらっています。