WordPress 发博客后自动同步到新浪微博,这是我从无主题博客看到的方法,一直沿用至今。感觉对博客宣传和提升“逼格”都有显著的作用:
一、老版代码
先来看一下无主题博客分享的代码:
function post_to_sina_weibo($post_ID) {
   if (wp_is_post_revision($post_ID)) return;  //修订版本(更新)不发微博
   $get_post_info = get_post($post_ID);
   $get_post_centent = get_post($post_ID)->post_content;
   $get_post_title = get_post($post_ID)->post_title;
   if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
     $appkey='3838258703';
     $username='微博用户名';
     $userpassword='微博密码';
     $request = new WP_Http;
     $status = '【' . strip_tags($get_post_title) . '】 ' . mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 132, '...') . ' 全文地址:' . get_permalink($post_ID);
     $api_url = 'https://api.weibo.com/2/statuses/update.json';
     $body = array('status' => $status,'source' => $appkey);
     $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
     $result = $request->post($api_url, array('body' => $body,'headers' => $headers));
   }
}
add_action('publish_post', 'post_to_sina_weibo', 0);//给发布文章增加一个分享微博的动作
同步之后是这样的效果:
由于我的博客关闭了修订版本,所以必须修改一下才能用,和之前修改百度 sitemap 插件原理一致(请注意 2~3 行):
function post_to_sina_weibo($post_ID) {
   /* 鉴于很多朋友反馈发布文章空白,临时加上调试代码,若无问题可删除此行,若有问题请将错误信息在本文留言即可 */
   ini_set('display_errors', true);
   /* 此处修改为通过文章自定义栏目来判断是否同步 */
   if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;
   $get_post_info = get_post($post_ID);
   $get_post_centent = get_post($post_ID)->post_content;
   $get_post_title = get_post($post_ID)->post_title;
   if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
     $appkey='1034947262';  /* 此处是你的新浪微博 appkey,不修改的话就会显示来自张戈博客哦! */
     $username='微博用户名';
     $userpassword='微博密码';
     $request = new WP_Http;
     
     /* 获取文章标签关键词 */
     $keywords = ""; 
     $tags = wp_get_post_tags($post_ID);
     foreach ($tags as $tag ) {
        $keywords = $keywords.'#'.$tag->name."#";
     }
     /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */
     $string1 = '【文章发布】' . strip_tags( $get_post_title ).':';
     $string2 = $keywords.' 查看全文:'.get_permalink($post_ID);
     /* 微博字数控制,避免超标同步失败 */
     $wb_num = (138 - WeiboLength($string1.$string2))*2;
     $status = $string1.mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, $wb_num,'...').$string2;
     $api_url = 'https://api.weibo.com/2/statuses/update.json';
     $body = array('status' => $status,'source' => $appkey);
     $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
     $result = $request->post($api_url, array('body' => $body,'headers' => $headers));
     /* 若同步成功,则给新增自定义栏目 weibo_sync,避免以后更新文章重复同步 */
     add_post_meta($post_ID, 'weibo_sync', 1, true);
   }
}
add_action('publish_post', 'post_to_sina_weibo', 0);
/*
//获取微博字符长度函数 
*/
function WeiboLength($str)
{
    $arr = arr_split_zh($str);   //先将字符串分割到数组中
    foreach ($arr as $v){
        $temp = ord($v);        //转换为 ASCII 码
        if ($temp > 0 && $temp < 127) {
            $len = $len+0.5;
        }else{
            $len ++;
        }
    }
    return ceil($len);        //加一取整
}
/*
//拆分字符串函数,只支持 gb2312 编码  
//参考:http://u-czh.iteye.com/blog/1565858
*/
function arr_split_zh($tempaddtext){
    $tempaddtext = iconv("UTF-8", "GBK//IGNORE", $tempaddtext);
    $cind = 0;
    $arr_cont=array();
    for($i=0;$i<strlen($tempaddtext);$i++)
    {
        if(strlen(substr($tempaddtext,$cind,1)) > 0){
            if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取 1 个字节
                array_push($arr_cont,substr($tempaddtext,$cind,1));
                $cind++;
            }else{
                array_push($arr_cont,substr($tempaddtext,$cind,2));
                $cind+=2;
            }
        }
    }
    foreach ($arr_cont as &$row)
    {
        $row=iconv("gb2312","UTF-8",$row);
    }
    return $arr_cont;
}
我修改的内容,在代码中都有相应的注释,一看即懂!
修改目的:一是为了此功能在【某些禁用了修订功能的 WordPress 博客】中,不会因为更新文章造成重复同步微博的窘迫;二是加上字数的控制,避免字数超过 140 导致同步失败。
同步之后是这样的效果:
以上代码的使用都非常简单,只要添加到主题目录的 functions.php 当中即可。至于如何实现【来自 XX 博客】这种提升逼格的效果,就需要去新浪微博开放平台申请网站应用接入了:
具体操作步骤,请去无主题博客看相关教程,我这就不赘述了==>传送门走起!
二、新版代码
以上代码同步的时候没有图片,稍感缺憾。
昨天闲来无事,看了下新浪的 API 文档,找到了符合要求的 API 接口:
Ps:API 文档地址:http://open.weibo.com/wiki/2/statuses/upload_url_text
细看参数说明,将之前的代码修改下就搞定了,代码如下(请注意 6~7 行):
2016 年 12 月 18 日更新:
1、新增同步日志方便查看失败原因;
2、新增对同步结果的判断,若失败则不会加自定义栏目。
Ps:请使用如下最新代码覆盖老代码。
/**
* WordPress 发布文章同步到新浪微博(带图片&自定义栏目版)
* 文章地址:https://zhang.ge/4947.html
* 最后更新:2016 年 12 月 18 日
*/
function post_to_sina_weibo($post_ID) {
   /* 鉴于很多朋友反馈发布文章空白,临时加上调试代码,若无问题可删除此行,若有问题请将错误信息在本文留言即可 */
   ini_set('display_errors', true);
   /* 此处修改为通过文章自定义栏目来判断是否同步 */
   if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;
   $get_post_info = get_post($post_ID);
   $get_post_centent = get_post($post_ID)->post_content;
   $get_post_title = get_post($post_ID)->post_title;
   if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
       $appkey='1034947262'; /* 此处是你的新浪微博 appkey,不修改的话就会显示来自张戈博客哦! */
       $username='微博用户名';
       $userpassword='微博密码';
       $request = new WP_Http;
       $keywords = ""; 
       /* 获取文章标签关键词 */
       $tags = wp_get_post_tags($post_ID);
       foreach ($tags as $tag ) {
          $keywords = $keywords.'#'.$tag->name."#";
       }
      /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */
     $string1 = '【文章发布】' . strip_tags( $get_post_title ).':';
     $string2 = $keywords.' 查看全文:'.get_permalink($post_ID);
     /* 微博字数控制,避免超标同步失败 */
      $wb_num = (138 - WeiboLength($string1.$string2))*2;
      $status = $string1.mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, $wb_num,'...').$string2;
     
       /* 获取特色图片,如果没设置就抓取文章第一张图片 */ 
       $url = get_mypost_thumbnail($post_ID);
    
       /* 判断是否存在图片,定义不同的接口 */
       if(!empty($url)){
           $api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json'; /* 新的 API 接口地址 */
           $body = array('status' => $status,'source' => $appkey,'url' => $url);
       } else {
           $api_url = 'https://api.weibo.com/2/statuses/update.json';
           $body = array('status' => $status,'source' => $appkey);
       }
       $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
       $results = $request->post($api_url, array('body' => $body,'headers' => $headers));
       $result  = $results['body'];
        if(!strstr($result ,'error_code')) {
            // 若成功,则给新增自定义栏目 weibo_sync,避免以后更新文章重复同步
            add_post_meta($post_ID, 'weibo_sync', 1, true);
        } else {
            // 若失败,则记录错误日志
            logInfo($result);
        }  
       add_post_meta($post_ID, 'weibo_sync', 1, true);
    }
}
add_action('publish_post', 'post_to_sina_weibo', 0);
/*
//获取微博字符长度函数 
*/
function WeiboLength($str)
{
    $arr = arr_split_zh($str);   //先将字符串分割到数组中
    foreach ($arr as $v){
        $temp = ord($v);        //转换为 ASCII 码
        if ($temp > 0 && $temp < 127) {
            $len = $len+0.5;
        }else{
            $len ++;
        }
    }
    return ceil($len);        //加一取整
}
/*
//拆分字符串函数,只支持 gb2312 编码  
//参考:http://u-czh.iteye.com/blog/1565858
*/
function arr_split_zh($tempaddtext){
    $tempaddtext = iconv("UTF-8", "GBK//IGNORE", $tempaddtext);
    $cind = 0;
    $arr_cont=array();
    for($i=0;$i<strlen($tempaddtext);$i++)
    {
        if(strlen(substr($tempaddtext,$cind,1)) > 0){
            if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取 1 个字节
                array_push($arr_cont,substr($tempaddtext,$cind,1));
                $cind++;
            }else{
                array_push($arr_cont,substr($tempaddtext,$cind,2));
                $cind+=2;
            }
        }
    }
    foreach ($arr_cont as &$row)
    {
        $row=iconv("gb2312","UTF-8",$row);
    }
    return $arr_cont;
}
/**
* WordPress 获取文章图片加强版 By 张戈博客
*/
if(!function_exists('get_mypost_thumbnail')){
  function get_mypost_thumbnail($post_ID){
     if (has_post_thumbnail()) {
            $timthumb_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'full' ); 
            $url = $timthumb_src[0];
    } else {
        if(!$post_content){
            $post = get_post($post_ID);
            $post_content = $post->post_content;
        }
        preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', do_shortcode($post_content), $matches);
        if( $matches && isset($matches[1]) && isset($matches[1][0]) ){       
            $url =  $matches[1][0];
        }else{
            $url =  '';
        }
    }
    return $url;
  }
}
//写日志函数
function logInfo($msg)
{
    $logSwitch  = 1;                     // 日志开关:1 表示打开,0 表示关闭
    $logFile    = '/tmp/sync_weibo.log'; // 日志路径           
    if ($logSwitch == 0 ) return;
    date_default_timezone_set('Asia/Shanghai');
    file_put_contents($logFile, date('[Y-m-d H:i:s]: ') . $msg . PHP_EOL, FILE_APPEND);
    return $msg;
}
三、权限申请
一切准备就绪了,但是发布文章肯定不会同步,为啥?因为没权限呗~!原来这个接口需要在原先的基础上额外申请。
如果,你的网站已经在微博申请接入了,那么只要点击应用名称:
然后,在接口管理==>申请权限==>申请微博高级写入权限:
有求于人,不管有多容易、门槛有多低,我们都要保持诚恳的态度:
通过之后,你在去发布文章,就能看到效果了,不但有特色图片,而且还显示【来自 XX 博客】:
是不是再一次满足了你的逼格需求呢?哈哈!
2016 年 01 月 16 日 内容补充:最近发现了一个导致微博同步失败的原因,并分享了微博同步失败的终极 DeBUG 大法,详情请看:https://zhang.ge/5082.html













分享的内容,想包含meta部分,请问代码怎么修改的。比如关键词,或者描述
竟然说是文本过长,无语了,代码里不是有自动截取文字的吗?
wordpress文章微博同步,完全是实现了。只是在文章定时发布这一块,同步微博,固定链接如果是:/%category%/%post_id%,在定时发布同步到微博之后,固定链接就变成了/%post_id%。要是wordpress定时发布文章,微博同步之后,如果还需要文章链接保持:/%category%/%post_id%,那不知道在上面的代码基础上,改动哪里是可以实现的呢。
你需要研究为啥 get_permalink($post_ID) 这样拿不到你的那个分类前缀,导致url不完整。文章中的代码是使用wp内置函数获取当前文章地址,获取后没有分类前缀,肯定是你网站改动了哪里的问题,比如隐藏分类前缀。。。自行研究下吧。
现在用的是鸟哥的Begin主题,上后台一看设置,还真是被隐藏分类前缀了。只是为什么写好文章之后发布,会成功同步文章链接,而在定时发布文章的时候,就丢失了分类链接,这个不知道是什么原理
感觉很不错,先研究研究一下呀。
能不能不自动同步,文章太多有些就不要同步,但一发表就同步了。
加多点判断条件吧,或者在文章内容结尾加特殊标记、标识,在语句中判断文章内容有没有这个标记,就会决定发不发了
我不是想让每篇文章都同步,我想能不能写个判断,如果weibo等于1就同步,如果没有自定义weibo就不同步呢?目前的情况是只要发布文章就自动同步了
在文章内容结尾加特殊标记、标识,在语句中判断文章内容有没有这个标记,就会决定发不发了
那个weibo_sync明显没有什么用
代码已经存在避免同步的机制,如果不想同步的文章,在点击发布之前,先手工在编辑界面新增一个自定义栏目weibo_sync,值为1,就不会同步了。
我已经另外增加了自定义栏目,如果不为空就同步。同步后会自动新增自定义栏目weibo_sync,值为1,就不会同步了。
博主有没有兴趣搞一下那个同步到微博头条的呀!
post_content; $get_post_title = get_post($post_ID)->post_title; if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') { $appkey='3838258703'; $username='微博用户名'; $userpassword='微博密码'; $wb_num = (138 - WeiboLength($string1.$string2))*2; $request = new WP_Http; $status = '【' . strip_tags($get_post_title) . '】 ' . mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, $wb_num, '...') . ' 全文地址:' . get_permalink($post_ID); $api_url = 'https://api.weibo.com/2/statuses/update.json'; $body = array( 'title' => strip_tags($get_post_title), 'content'=>strip_tags(apply_filters('the_content', $get_post_centent)), 'cover'=>'', 'summary'=>mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, $wb_num, '...') 'text'=>mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, $wb_num,'...') 'source' => $appkey ); $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword")); $result = $request->post($api_url, array('body' => $body,'headers' => $headers)); } } add_action('publish_post', 'post_to_sina_weibo_toutiao', 0);//给发布文章增加一个分享微博头条文章的动作 ?>我使用这个代码时,发现有错误,就是按个'text'的地方有语法错误!用测试代码也是这里提示text参数错误!
这个也是在高级接口里需要申请的一个,就是同步到微博头条文章里的!我获得这个接口权限了今天!
谢谢了!等回信儿哈! :grin: :razz: :arrow:
呃。。。新浪貌似api说明不更新,我想普通接口发个图也不行
if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;
这句挺矛盾的,发布的时候才会加自定义内容,但是文章ID是不会重复的,这个读取明显多此一举
明显就没细看文章。。。加这个是避免重复同步到微博。如果文章已经存在weibo_sync这个自定义内容,就不会再往微博同步。
但是发布行为里读取这个标,肯定是没有这个标的值的啊。新写文章就算是写的重复文章。。。也。
add_action('publish_post'
这个检验里如果是修改更新文章时是有用的。
是的,初衷是为了避免更新文章也同步微博做的。第一次发布文章是肯定会同步的,除非手工添加这个值,才能跳过同步。
哥,带我飞,普通接口的带图微博,pic binary发布例子能写一个不
does multipart has image?
最近一直出现这个错误,是怎么回事儿呀?我另一个站主题一样,配置一样,代码也一样就没有这个问题!
博主求救了!
张大哥,我看到你微博api对接的文章,深受批启发,可是还是有点有问题一直困扰。加了你微信你一直没加上。麻烦通过下。或者加下我微信onemegood 希望帮我解开下疑问
可以使用QQ临时聊天,在关于博客就有链接
拜托拜托
现在高级写入接口申请需要应用有1000个用户才可以通过。
老大,我的博客用了你的插件新文章都不同步,我用的采集插件会自动同步到微博去。
还有,每次发布新文章后 就会白屏 你说的会打印出错误,具体位置是哪里呢,日志也没有生成过! :!: :!: :!:
发现我之前发的评论没了... 我重新写一下
我每次发布文章后都会白屏,但是又没有找到错误日志... 并且没看到打印出来的错误啊!
开启php错误日志看看,目测函数冲突或有其他错误,自行研究吧
你博客的https坏了啊…… chrome浏览器阻止访问。
我这里没问题,能否帮忙提供下ping我域名的IP地址是多少,我排查下。
发图片到你邮箱了=,=
已更换证书,不知道好了没,我这里一直没报错。。。估计和谷歌版本有关系。
好了
张哥,现在微博的高级写入程序已下线了,还能实现带特色图片吗?同步是没问题
同问,高级接口申请不到了。回复“申请驳回
该接口功能即将下线,请使用微博SDK分享实现。”怎么办?
我使用wordpress Mu,而且多站点都使用了同一套主题,请问
1.是否支持wordpress MU?
2.对于custom post type的发布是否支持?还是只支持wordpress blog的post?
多谢。?
微博接口升级了,有新版代码吗
现在好像不能用了,同步不了了,不知道就我一个人用不了了,还是我部署的有问题。
申请权限处找不到“微博高级写入接口”啊!
很好的功能,现在还能用么?
用了新代码,每篇同步到微博的都是超时5000MS = =
{"errors":{"http_request_failed":["cURL error 28: Operation timed out after 5000 milliseconds with 0 bytes received"]},"error_data":[]}你可以在服务器上用curl命令手工请求下微博接口,看看是不是不通。
http://open.weibo.com/wiki/Announcement-oauth basic借口应该关闭了啊,这个怎么还可以使用呢
不知道还能不能使用。。很久没看了
现在还能同步吗
现在微博接口更新了
现在还可以同步吗?
有个问题想问一下 我用curl重新弄了一个 headers里发送的内容是账号密码 body里发送的是appkey和内容 结果返回{"error":"auth by Null spi!","error_code":21301,"request":"/2/statuses/update.json"}请问博主是post账号密码是不能用了 还是要用oauth获取key然后作为用户凭据提交? access_token这个参数文档里是必填啊