先日設置しましたメニューバー下の新着記事サムネイルに、その記事のツイート数を表示してみました!
いろんなサイトを見て「いいなぁ」と思っていたのでけっこー感動。いいわぁwということで、記事のツイート数を取得して表示する方法と、この斜め三角をどうやって作ったかを解説したいと思います!
これだと、記事にアクセスがあったときに毎回 Twitter API 叩いて、Twitter サーバーにいらん負荷をかけちゃうので、WordPress の Transient API 使って、キャッシュを取得するようにしたほうが良いと思う。
あと WP 使うんなら file_get_contents() ではなく、wp_remote_get() 使ったほうが、何かと便利。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /* | |
| * Get Social Button Count twitter | |
| */ | |
| function get_social_counts( $url ){ | |
| $transient_key = md5('get_social_counts-' . $url); | |
| // get cache | |
| if ( false === ($counts = get_transient($transient_key)) ) { | |
| $counts = array(); | |
| //twitter tweetcount | |
| $response = wp_remote_get('http://urls.api.twitter.com/1/urls/count.json?url=' . urlencode($url)); | |
| if( !is_wp_error( $response ) && $response['response']['code'] === 200 ) { | |
| $decode_tweetcount = json_decode($response['body']); | |
| $twitter_tweetcount = | |
| isset($decode_tweetcount['count']) | |
| ? $decode_tweetcount['count'] | |
| : 0; | |
| } else { | |
| $twitter_tweetcount = 0; | |
| } | |
| //set array | |
| $counts['twitter'] = $twitter_tweetcount; | |
| // set cache | |
| set_transient($transient_key, $counts, 60*60*1); // expires 60sec * 60min * 1 = 1hour | |
| } | |
| return $counts; | |
| } |
※未検証です。
コメントをどうぞ