-
Notifications
You must be signed in to change notification settings - Fork 0
/
latest-tweet.js
69 lines (66 loc) · 2.31 KB
/
latest-tweet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//jQuery plugin (wrapped in a self-invoking function) fetches latest tweet
(function($){
$.fn.latestTweet = function(username, num) {
if(!username || username === "") {username="nydame";} // default is the developer :P
if(!num || num<=0) {num = 20;} // default is 20
var $orig = this;
var tweetString = "",
tweetUrl = 'http://api.twitter.com/1/statuses/user_timeline.json?callback=?';
// Source: http://stackoverflow.com/a/37687/27736
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
function tweetFailHandler() {
if(document.getElementById('twitter')) {
$('#twitter').hide();
}
return $orig;
}
function tweetHandler(data) {
if(!data || data.length <= 0) {tweetFailHandler();}
var d1 = [],
dateString = "",
i = 0, //index of latest tweet
patt = /^@/;
//filter out retweets (null text) and replies (start with "@")
try {
while( data[i].text===null || patt.test(data[i].text) ) {
i++;
if( i == num ) {break;}
}
} catch(e1) {
tweetFailHandler();
}
if( i == num ) {tweetFailHandler();}
//with value of i set, compose text
//1st turn date of latest tweet into an array of its components
try {
d1 = (data[i].created_at).split(' ');
dateString += '<span class="ltw-date"> — ' + d1[0] + ' ' + d1[1] + ' ' + d1[2] + ', ' + d1[5] + '</span>';
} catch(e2) {
tweetFailHandler();
}
tweetString += data[i].text + dateString;
//finally, display tweet and return caller
if( tweetString !== "" && document.getElementById('twitter') ) {
tweetString = replaceURLWithHTMLLinks(tweetString);
$('#twitter').empty();
$('<p class="ltw-status"><span class="ltw-header">Latest Tweet</span> </p>').appendTo('#twitter');
$('#twitter p.ltw-status').append(tweetString);
}
} //end tweetHandler
//fetch latest tweet
$.getJSON(
tweetUrl,
{count:num, screen_name:username},
tweetHandler
);
return $orig;
}; //end plugin
})(jQuery);
//call plugin using no-conflict wrapper recommended in WP Codex
jQuery(document).ready(function($) {
// $() will work as an alias for jQuery() inside of this function
$(document).latestTweet(); //default username and number to search
});