Twitterでの記事のツイート数を表示させる

Twitterではシェアボタンが用意されていますが、
このシェアボタンで呟かれた数を記事ごとに表示させる方法を紹介します。
テーマ内に functions.php を用意する
現在使っているテーマの「functions.php」を用意します。
無い場合は「functions.php」の名前でテーマフォルダ内に作成します。
functions.php にメソッドを追加する
twitterAPIを使用したメソッドを作成します。
<?php
// twitterでのツイート数を取得する
function get_social_counts($url){
$counts = '';
$encode_url = urlencode($url);
// APIからツイート数を取得
$count = file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encode_url, true);
$count = json_decode($count, true);
$count = $count['count'];
return $count;
}
?>
テーマに組み込む
<?php if (have_posts()) :
while (have_posts()) : the_post(); ?>
<div class="post">
<?php
// 記事のツイート数を取得
$count = get_social_counts();
$count = htmlspecialchars($count, ENT_QUOTES);
if ( empty($count) ):
$count = 0;
endif;
?>
<div class="title"><?php the_title() ?></div>
<div class="date"><?php the_time('Y.m.d') ?></div>
<div class="count"><?php echo $count; ?></div>
</div>
<?php endwhile; ?>
<?php endif; ?>
これでツイート数が表示されます。
関連記事






