发布博客文章时自动同步到 Twitter

有一大把插件可以实现发布博客文章时自动同步到 Twitter 的功能,如果你不想用插件,那么还有 twitterfeed 可以选择,如果你连 twitterfeed 都不想用,那么只好自己添加几行代码了。

//添加到 functions.php
function publish_to_twitter($postID){
$user = ‘user’;
$passwd = ‘xxx’;
$post = get_post($postID);
$title = $post->post_title;
$link = getShortenUrl($postID);
$word_limit = 110 – mb_strlen($title) – strlen($link);
$content = strip_tags($post->post_content);
$content = preg_replace(‘/\s+/’,’ ‘,$content);
if (mb_strlen($content) > $word_limit) {
$content=mb_strimwidth($content, 0, $word_limit, ‘…’);
}
$status = $title . ” | Centeur’s Chaos: ” . $content . ‘ ‘ . $link;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘http://twitter.com/statuses/update.xml’);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERPWD, “$user:$passwd”);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, ‘status=’. urlencode($status));
curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
switch($httpcode):
case 200:
echo ‘Your status has been updated’;
break;
case 401:
echo ‘Not Authorized: invalid username or password.’;
break;
default:
echo ‘An unknown error has occured. Try Again’;
endswitch;
}

add_action(‘publish_post’, ‘publish_to_twitter’);

getShortenUrl($postID) 这个函数参考这里

Tags: ,

This entry was posted on Tuesday, June 2nd, 2009 at 8:06 am and is filed under wordpress. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Posts you may enjoy

Leave a Reply

Please copy the string JQi5di to the field below: