WordPress: publish a tweet as a post

Twitter is surely one the most popular social networks on the web, and WordPress is surely one the most popular CMS available today. Usually these two platforms interact only in one way: you get something from Twitter, you post something on Twitter. Let's say that you want to publish your latest tweet as a post on your WordPress site, also checking if there is another brand new tweet available. How we can to this?

The first thing you need to do is to create a category for your tweets. Let's name this category tweets and assume that its assigned category ID is 145 (you can see the ID by hovering the category link with your mouse on the WordPress backend).

Then add the following code to the functions.php file of your theme:

function get_insert_latest_tweet() {
 global $wpdb;
 $post = array();
 $url = "http://twitter.com/statuses/user_timeline/yourusername.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 'less than a minute ago.';
  } else if ($delta < 120) {
    return 'about 1 minute ago.';
  } else if ($delta < (45 * 60)) {
    return floor($delta / 60) . ' minutes ago.';
  } else if ($delta < (90 * 60)) {
    return 'about 1 hour ago.';
  } else if ($delta < (24 * 60 * 60)) {
    return 'about ' . floor($delta / 3600) . ' hours ago.';
  } else if ($delta < (48 * 60 * 60)) {
    return '1 day ago.';
  } else {
    return floor($delta / 86400) . ' days ago.';
  }
}

get_insert_latest_tweet() create a new post from your Twitter feed through the wp_insert_post() function. Before creating a new post, though, it checks whether the current tweet has already been inserted. If so, it does nothing.

The WordPress action used here is pre_get_posts which means that the current tweet is fetched within your main WordPress Loop. You can change this behavior by moving the above function in a separate plugin that requires your deliberate action to create a new post from a tweet.

Leave a Reply

Note: Only a member of this blog may post a comment.