Last active
December 11, 2015 09:08
-
-
Save esgy/4577413 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Plugin Name: Twitter Shower | |
* Plugin URI: http://esgy.eu | |
* Description: Simple shortcode | |
* Version: 1.0 | |
* Author: Sorin Gitlan | |
* Author URI: http://esgy.eu | |
*/ | |
add_shortcode('twitter', function($atts, $content){ | |
$atts = shortcode_atts( | |
array( | |
'username' => 'esgy_eu', | |
'content' => !empty($content) ? $content : 'Follow me on Twitter!', | |
'show_tweets' => true, | |
'tweet_reset_time' => 10, | |
'num_tweets' => 5 | |
), $atts | |
); | |
extract($atts); | |
if($show_tweets){ | |
$tweets = fetch_tweets($num_tweets, $username, $tweet_reset_time); | |
} | |
return $tweets . '<p><a href="http://twitter.com/'. $username .'" target="_blank">'. $content .'</a></p>'; | |
}); | |
function fetch_tweets($num_tweets, $username, $tweet_reset_time){ | |
global $id; | |
$recent_tweets = get_post_meta( $id, 'jw_recent_tweets'); | |
reset_data($recent_tweets, $tweet_reset_time); | |
// if no cache fetch new tweets | |
if(empty($recent_tweets)){ | |
$tweets = curl('https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=1&screen_name=@'.$username.'&count='. $num_tweets .'&published_when=1'); | |
//echo '<pre>'; | |
//print_r(json_decode($tweets)); | |
//echo '</pre>'; | |
$data = array(); | |
foreach (json_decode($tweets) as $tweet) { | |
$data[] = $tweet->text."<br>"; | |
} | |
$recent_tweets = array( (int)date( 'i', time() ) ); | |
$recent_tweets[] = '<ul class="jw_tweets"><li>'. implode('</li><li>', $data) . '</li></ul>'; | |
cache($recent_tweets); | |
} | |
return isset($recent_tweets[0][1]) ? $recent_tweets[0][1] : $recent_tweets[1]; | |
} | |
function curl($url){ | |
$curl = curl_init($url); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); | |
return curl_exec($curl); | |
curl_close($curl); | |
} | |
function cache($recent_tweets){ | |
// [0] = current minute | |
// [1] = tweet html fragment | |
global $id; | |
add_post_meta( $id, 'jw_recent_tweets', $recent_tweets, true ); | |
} | |
function reset_data($recent_tweets, $tweet_reset_time){ | |
global $id; | |
if( isset($recent_tweets[0][0]) ){ | |
$delay = $recent_tweets[0][0] + (int)$tweet_reset_time; | |
if($delay >= 60) $delay -= 60; | |
if($delay <= (int)date( 'i', time() )){ | |
delete_post_meta( $id, 'jw_recent_tweets'); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment