
Di sicuro plugin per integrare Twitter in WordPress ce ne sono moltissimi, alcuni interessanti, altri con tante funzioni non necessarie. In questo breve tutorial vedremo come integrare e visualizzare i Twitt nella sidebar usando del semplice codice e le API di Twitter.
Codice
In questo esempio inseriremo il nostro codice come widget nella sidebar, è comunque possibile aggiungerlo anche in altre parti del nostro template. Apri il file sidebar.php del tuo tema e inserisci questo codice nel punto dove vuoi venga visualizzato, generalmente all’interno di un elemento lista.
[php]
-
- /*
-
- * JSON list of tweets using:
-
- * http://dev.twitter.com/doc/get/statuses/user_timeline
-
- * Cached using WP transient API.
-
- * http://www.problogdesign.com/wordpress/use-the-transients-api-to-list-the-latest-commenter/
-
- */
// Configuration.
$numTweets = 5;
$name = ‘tuoIDtwitter’;
$transName = ‘list-tweets’; // Name of value in database.
$cacheTime = 5; // Time in minutes between updates.
// Do we already have saved tweet data? If not, lets get it.
if(false === ($tweets = get_transient($transName) ) ) :
// Get the tweets from Twitter.
$json = wp_remote_get(“http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$name&count=$numTweets”);
// Get tweets into an array.
$twitterData = json_decode($json[‘body’], true);
// Now update the array to store just what we need.
// (Done here instead of PHP doing this for every page load)
foreach ($twitterData as $tweet) :
// Core info.
$name = $tweet[‘user’][‘name’];
$permalink = ‘http://twitter.com/#!/’. $name .’/status/’. $tweet[‘id_str’];
/* Alternative image sizes method: http://dev.twitter.com/doc/get/users/profile_image/:screen_name */
$image = $tweet[‘user’][‘profile_image_url’];
// Message. Convert links to real links.
$pattern = ‘/http:(\S)+/’;
$replace = ‘${0}‘;
$text = preg_replace($pattern, $replace, $tweet[‘text’]);
// Need to get time in Unix format.
$time = $tweet[‘created_at’];
$time = date_parse($time);
$uTime = mktime($time[‘hour’], $time[‘minute’], $time[‘second’], $time[‘month’], $time[‘day’], $time[‘year’]);
// Now make the new array.
$tweets[] = array(
‘text’ => $text,
‘name’ => $name,
‘permalink’ => $permalink,
‘image’ => $image,
‘time’ => $uTime
);
endforeach;
// Save our new transient.
set_transient($transName, $tweets, 60 * $cacheTime);
endif;
// Now display the tweets.
foreach($tweets as $t) : ?>
-
ago
[/php]
La configurazione è molto semplice, ti basterà inserire il tuo ID Twitter in questa stringa $name = ‘tuoIDtwitter’; che trovi all’inizio dello script, sostituendo tuoIDtwitter.
Le altre variabili di configurazione sono:
$numTweets = 3; per il numero di tweet da visualizzare
$cacheTime = 5; per i minuti di aggiornamento tweet
Per ulteriori spiegazioni sul funzionamento visita Problogdesign
