WordPress发布文章自动同步到新浪微博(带特色图片)

次阅读

WordPress 发博客后自动同步到新浪微博,这是我从无主题博客看到的方法,一直沿用至今。感觉对博客宣传和提升“逼格”都有显著的作用:

weibo1

一、老版代码

先来看一下无主题博客分享的代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
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);//给发布文章增加一个分享微博的动作

同步之后是这样的效果:

weibo2

由于我的博客关闭了修订版本,所以必须修改一下才能用,和之前 修改百度 sitemap 插件 原理一致(请注意 2~3 行):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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 导致同步失败。

同步之后是这样的效果:

weibo3

以上代码的使用都非常简单,只要添加到主题目录的 functions.php 当中即可。至于如何实现【来自 XX 博客】这种提升逼格的效果,就需要去 新浪微博开放平台 申请网站应用接入了:

weibo4 具体操作步骤,请去无主题博客看相关教程,我这就不赘述了==> 传送门 走起!

二、新版代码

以上代码同步的时候没有图片,稍感缺憾。

昨天闲来无事,看了下新浪的 API 文档,找到了符合要求的 API 接口:

weibo5

Ps:API 文档地址: http://open.weibo.com/wiki/2/statuses/upload_url_text

细看参数说明,将之前的代码修改下就搞定了,代码如下(请注意 6~7 行):

2016 年 12 月 18 日更新:

1、新增同步日志方便查看失败原因;

2、新增对同步结果的判断,若失败则不会加自定义栏目。

Ps:请使用如下最新代码覆盖老代码。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/**
* WordPress发布文章同步到新浪微博(带图片&自定义栏目版)
* 文章地址:/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;
}

三、权限申请

一切准备就绪了,但是发布文章肯定不会同步,为啥?因为没权限呗~!原来这个接口需要在原先的基础上额外申请。

如果,你的网站已经在微博申请接入了,那么只要点击应用名称:

weibo6

然后,在接口管理==>申请权限==>申请微博高级写入权限:

weibo7

有求于人,不管有多容易、门槛有多低,我们都要保持诚恳的态度:

weibo8

一般情况,一个工作日之内就能通过了: weibo9

通过之后,你再去发布文章,就能看到效果了,不但有特色图片,而且还显示【来自 XX 博客】:

weibo10

是不是再一次满足了你的逼格需求呢?哈哈!

2016 年 01 月 16 日 内容补充:最近发现了一个导致微博同步失败的原因,并分享了微博同步失败的终极 DeBUG 大法,详情请看: /5082.html

最后更新于 2016年12月18日星期日