<?php
/*
Plugin Name: t.cn wordPress 插件
Plugin URI: http://fairyfish.net/2011/01/26/t-cn-wordpress-plugin/
Description: 获取日志的 t.cn 短域名
Version: 0.1
Author: Denis
*/

function get_t_cn($long_url){
	$api_url = 'http://api.t.sina.com.cn/short_url/shorten.json?source=744243473&url_long='.$long_url;
    $request = new WP_Http;
    $result = $request->request( $api_url);
	$result = $result['body'];
	$result = json_decode($result);
	return $result[0]->url_short;
}

function get_post_t_cn($post_ID){
	$t_cn = get_post_meta($post_ID, 't.cn', true);
	if(!$t_cn) {
		$long_url = get_permalink($post_ID);
		$t_cn = get_t_cn($long_url);
		add_post_meta($post_ID, 't.cn', $t_cn, true);
	}
	return $t_cn;
}

add_action('publish_post', 'publish_post_2_microblog', 0);
function publish_post_2_microblog($post_ID){
	get_post_t_cn($post_ID);
}

add_filter('the_content','t_cn_content');
function t_cn_content($text){
	if(is_single()||is_page()||is_feed()) {
		global $post;
		
		$t_cn = get_post_t_cn($post->ID);
		
		$text = $text . '<div class="t-cn-link">这篇日志的 t.cn 短域名为：<a href="'.$t_cn.'">'.$t_cn .'</a>。</div>';
	}
	return $text;	
}
