经常上并且关注了不少官网认证号的小伙伴一定会发现很多官方性质的微博都会把网站的最新文章或者动态同步到新浪微博这样一来就可以让微博用户快速的了解到网站的最新动态,并且也为网站增加了一个曝光以及流量入口,对于更新频繁的网站来说增加一个同步网站动态到微博的功能是非常有必要的。

wordpress发布文章后自动同步图文到新浪微博实用教程

多说中有个较为实用的功能——“同时发布到”,只需要绑定新浪微博、腾讯微博、百度……只需勾选编辑文章页上的选项,一键搞定。如果我们需要在主题中集成此功能呢?

废话少说,上代码:

实现方法

  把下面的代码加到主题 functions.php 中,注意添加 access_token 和默认图片地址两个参数, access_token 的获得方法参考相关文章(比如说 CNBlogs)。

class sync_sina {
 
    public $access_token = "";//access_token
    
    public $default_image = "";//默认图片地址
 
    public $host = "https://api.weibo.com/2/";
       
    public static $boundary = '';
       
    function __construct(){
        /**
         ** 事件绑定
         **/
        add_action('publish_post', array($this, 'new_post_photo'));
    }
 
    function do_mu_post($url, $data) {
        $ch = curl_init ();
        $headers = array("Content-Type:multipart/form-data;boundary=". self::$boundary);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
        curl_setopt ( $ch, CURLOPT_POST, TRUE );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $ret = curl_exec ( $ch );
        curl_close ( $ch );
        return $ret;
    }
 
    function build_http_query_multi($params) {
        if (!$params) return '';
        uksort($params, 'strcmp');
        $pairs = array();
        self::$boundary = $boundary = uniqid('------------------');
        $MPboundary = '--'.$boundary;
        $endMPboundary = $MPboundary. '--';
        $multipartbody = '';
        foreach ($params as $parameter => $value) {
            if( in_array($parameter, array('pic', 'image')) && $value{0} == '@' ) {
                $url = ltrim( $value, '@' );
                $content = file_get_contents( $url );
                $array = explode( '?', basename( $url ) );
                $filename = $array[0];
                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'Content-Disposition: form-data; name="' . $parameter . '"; filename="' . $filename . '"'. "\r\n";
                $multipartbody .= "Content-Type: image/unknown\r\n\r\n";
                $multipartbody .= $content. "\r\n";
            } else {
                $multipartbody .= $MPboundary . "\r\n";
                $multipartbody .= 'content-disposition: form-data; name="' . $parameter . "\"\r\n\r\n";
                $multipartbody .= $value."\r\n";
            }
        }
        $multipartbody .= $endMPboundary;
        return $multipartbody;
    }
 
    function get_image($post_id){
        if( has_post_thumbnail($post_id) ){
            $timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id),'full');
            $output = $timthumb_src[0];
        } else {
            $content = get_post_field('post_content', $post_id);
            $defaltthubmnail = $this->default_image;
            preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER);
            $n = count($strResult[1]);
            if($n > 0){
                $output = $strResult[1][0];
            } else {
                $output = $defaltthubmnail;
            }
        }
        return $output;
    }
 
    function new_post_photo($post) {
        global $post;
        if( $post->post_status != "publish" ){
            $token = $this->access_token;
            $url = $this->host ."statuses/upload.json";
            $status = "我刚刚发布了新文章《".get_the_title()."》。".get_permalink();
            $status .= mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0,180,"..."); //顺手加了个文章摘要,不喜欢就去掉啦
            $pic_path = self::get_image($post->ID);
            $params = array();
            $params['access_token'] = $token;
            $params['status'] = $status;
            $params['pic'] = '@'.$pic_path;
            $body = self::build_http_query_multi($params);
            $result = self::do_mu_post($url,$body);
 
        }
    }
}
$HMT = new sync_sina();

注意

    需要服务器支持file_get_contents函数以及curl组件;

    如果网站在国外服务器或者服务因特殊原因屏蔽了api.weibo.com域名,则可能造成发布文章卡死或者超时的问题。

    如果网站未通过新浪审核微博小尾巴会显示为未审核应用。

    文章来源:http://www.mywpku.com/wordpress-sync-sina-weibo.html