Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<?php
/**
* Plugin Name: Twitter Share Counts Tutorial
* Plugin URI: http://webdevstudios.com
* Version 0.1.0
* Author: JayWood
* Author URI: http://www.plugish.com
*/
require_once 'twitteroauth/autoload.php';
use Abraham\TwitterOAuth\TwitterOAuth;
class Twitter_Counts {
/**
* @var Twitter_Counts null
*/
public static $instance = null;
public $count = 0;
private $consumer_key = '';
private $consumer_secret = '';
private $access_token = '';
private $access_secret = '';
private function __construct() {
// Fancy stuff.
}
public static function get_instance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
public function save_count( $post_id, $args ) {
$save = array(
'count' => $this->count,
);
if ( isset( $args['max_id'] ) ) {
$save['max_id'] = $args['max_id'];
}
update_post_meta( $post_id, 'tweet_data', $save );
return $this->count;
}
public function tweet_count( $post_id, $args = array() ) {
$defaults = array(
'q' => get_permalink( $post_id ),
'count' => 100,
'include_entities' => true,
);
$meta = get_post_meta( $post_id, 'tweet_data' );
$meta = is_array( $meta ) ? array_shift( $meta ) : array();
$this->count = isset( $meta['count'] ) && 0 == $this->count ? $meta['count'] : $this->count;
if ( isset( $meta['max_id'] ) ) {
$defaults['max_id'] = $meta['max_id'];
}
$args = wp_parse_args( $args, $defaults );
$oauth = new TwitterOAuth( $this->consumer_key, $this->consumer_secret, $this->access_token, $this->access_secret );
$statuses = $oauth->get( 'search/tweets', $args );
if ( ! $statuses || ! isset( $statuses->statuses ) ) {
return $this->save_count( $post_id, $args );
}
$this->count = $this->count + count( $statuses->statuses );
$last_status = end( $statuses->statuses );
$last_id = isset( $last_status->id ) ? $last_status->id : false;
if ( ! isset( $args['max_id'] ) ) {
if ( $last_id ) {
$args['max_id'] = $last_id;
}
}
if ( isset( $statuses->search_metadata ) && isset( $statuses->search_metadata->next_results ) ) {
if ( isset( $last_id ) ) {
$this->tweet_count( $post_id, array( 'max_id' => $last_id ) );
}
}
return $this->save_count( $post_id, $args );
}
}
function Twitter_Counts() {
return Twitter_Counts::get_instance();
}
function display_tweet_counts( $post_id = 0 ) {
if ( empty( $post_id ) ) {
$post_id = get_the_ID();
}
$cache_key = md5( 'twitter_counts_' . $post_id );
$count = get_transient( $cache_key );
if ( false == $count ) {
$tc = Twitter_Counts();
$result = $tc->tweet_count( $post_id );
$count = false == $result ? 0 : $result;
set_transient( $cache_key, $count, 1 * HOUR_IN_SECONDS );
}
return $count;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment