WordPress: pubblicare un tweet come post

WordPress: pubblicare un tweet come post

Possiamo reperire il nostro ultimo tweet da Twitter e pubblicarlo come un normale post su WordPress con una procedura alquanto semplice. Vediamo quale.

Per prima cosa creiamo una categoria e un nuovo tag per questo tipo di post. Nel nostro esempio useremo tweets come categoria e tweet come tag. Questo ci permette anche di distinguere questo tipo di post dagli altri.

Apriamo il file functions.php del nostro tema e aggiungiamo il seguente codice:


function get_insert_latest_tweet() {
	global $wpdb;
	$post = array();
	$url = "http://twitter.com/statuses/user_timeline/username.xml?count=1";
	
	if(file_get_contents($url)) {
	
		$xml = new SimpleXMLElement(file_get_contents($url));
		$status = $xml->status->text;
		$time = nice_time(strtotime($xml->status->created_at));
		$tweet = preg_replace('/http:\/\/(.*?)\/[^ ]*/', '<a href="\\0">\\0</a>', $status);
		$title = preg_replace('/http:\/\/(.*?)\/[^ ]*/', '', $status);
		
		$result = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE post_title = '$title'");
		
		$post['post_title'] = $title;
		$post['post_content'] = '<p>' . $tweet . ' <small>' . $time . '</small></p>';
		$post['post_status'] = 'publish';
		$post['post_category'] = array(145);
		$post['tags_input'] = 'tweet';
		
		if(is_null($result)) {
			wp_insert_post($post);
		}
		
	} else {
	
		return;
	
	}
	
	
	
}

add_action( 'pre_get_posts', 'get_insert_latest_tweet');



function nice_time($time) {
  $delta = time() - $time;
  if ($delta < 60) {
    return 'meno di 1 minuto fa.';
  } else if ($delta < 120) {
    return 'circa 1 minuto fa.';
  } else if ($delta < (45 * 60)) {
    return floor($delta / 60) . ' minuti fa.';
  } else if ($delta < (90 * 60)) {
    return 'circa 1 ora fa.';
  } else if ($delta < (24 * 60 * 60)) {
    return 'circa ' . floor($delta / 3600) . ' ore fa.';
  } else if ($delta < (48 * 60 * 60)) {
    return '1 giorno fa.';
  } else {
    return floor($delta / 86400) . ' giorni fa.';
  }
}

Abbiamo intercettato il caricamento dei post tramite la action pre_get_posts e aggiunto la nostra funzione. Al suo interno, abbiamo per prima cosa reperito il tweet e formattato i suoi elementi. Quindi abbiamo eseguito una query sul database per esseri sicuri di non inserire due volte lo stesso tweet. Se non si tratta dello stesso tweet, abbiamo usato la funzione wp_insert_post() passandogli un array di argomenti contenente i dati del nostro post che abbiamo ottenuto dal tweet.

Ecco il risultato:

Il risultato finale: un tweet pubblicato come post

Ovviamente potete rendere manuale questa operazione associandola ad un'azione di un plugin.

Torna su