Go to Top

WordPressで記事のツイート・いいね!・はてブ数等を取得してみる

2013/1/23| Category:

2016/11/26: ツイート数とfacebook関連のデータが取得できない問題を確認しております。

今回は、記事に対するリアクションの数をWordpress(php)で表示する方法を紹介します。

STEP 1-1

記事へのリアクション総数を表示したい。

その場合には、まず以下を「function.php」に記述してください。

このコードでは、ツイート数 + いいね!数 + シェア数 + はてブ数 + コメント数 + ピンバック数 + トラックバック数をリアクションとして表示します。

function GetNumAllReactions($url, $comments) {
	// ツイート数取得
	$get_twitter = 'http://urls.api.twitter.com/1/urls/count.json?url=' . $url;
	$json = file_get_contents($get_twitter);
	$json = json_decode($json);
	$twitter = $json->{'count'};

	// facebook(いいね! + シェア)数取得
	$get_facebook = 'http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $url;
	$xml = file_get_contents($get_facebook);
	$xml = simplexml_load_string($xml);
	$facebook = $xml->link_stat->total_count;  // いいね!のみ:like_count, shareのみ:share_count

	// はてブ数取得
	$get_hatebu = 'http://api.b.st-hatena.com/entry.count?url=' . $url;
	$hatebu = file_get_contents($get_hatebu);
	if ($hatebu == "") { $hatebu = 0; }

	$reactions = $twitter + $facebook + $hatebu + $comments;
	print("$reactions");
}
STEP 1-2

あとは、数値を表示したい箇所に以下のコードを記述すればOKです。

<?php GetNumAllReactions(get_permalink(), get_comments_number()); ?>
STEP 2-1

全てのリアクションではなく、ツイート数のみ、あるいはfacebook数のみ、はてブ数のみを表示したい。

という場合は、以下のコードの「19行目」の変数を対応するものに変更し、不要な部分を削除した上で「function.php」に記述してください。

又、ツイート数 + facebook数というように、複数の値を足した数値を表示したい場合には、先ほどのプログラムを参考に自分で編集してみてください。

function GetNumReactions($url) {
	// ツイート数取得
	$get_twitter = 'http://urls.api.twitter.com/1/urls/count.json?url=' . $url;
	$json = file_get_contents($get_twitter);
	$json = json_decode($json);
	$twitter = $json->{'count'};

	// facebook(いいね! + シェア)数取得
	$get_facebook = 'http://api.facebook.com/restserver.php?method=links.getStats&urls=' . $url;
	$xml = file_get_contents($get_facebook);
	$xml = simplexml_load_string($xml);
	$facebook = $xml->link_stat->total_count;  // いいね!のみ:like_count, shareのみ:share_count

	// はてブ数取得
	$get_hatebu = 'http://api.b.st-hatena.com/entry.count?url=' . $url;
	$hatebu = file_get_contents($get_hatebu);
	if ($hatebu == "") { $hatebu = 0; }

	print("$表示したい変数の名前");  // $twitter, $facebook, $hatebu
}
STEP 2-2

あとは先程と同様に、数値を表示したい箇所に以下のコードを記述すればOKです。

<?php GetNumReactions(get_permalink()); ?>
Pocket