使用新浪微博开放平台api同步微博内容至自己网站( 修改一下才能用,和之前修改百度sitemap插件原理一致)

优采云 发布时间: 2022-03-12 04:09

  使用新浪微博开放平台api同步微博内容至自己网站(

修改一下才能用,和之前修改百度sitemap插件原理一致)

  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') {

     $a*敏*感*词*ey='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' => $a*敏*感*词*ey);

     $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);//给发布文章增加一个分享微博的动作

  同步后是这样的效果:

  由于我的博客已经关闭了修改版,所以必须修改后才能使用,这和之前修改百度站点地图插件的原则是一致的(请注意第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') {

     $a*敏*感*词*ey='1034947262';  /* 此处是你的新浪微博a*敏*感*词*ey,不修改的话就会显示来自张戈博客哦! */

     $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' => $a*敏*感*词*ey);

     $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 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博客】的效果,需要到新浪微博开放平台申请网站应用权限:

  具体操作步骤请到无题博客查看相关教程,这里不再赘述==&gt;传送门开始!

  二、新代码

  上面代码同步的时候没有图片,有点遗憾。

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

  ps:API文档地址:

  仔细看参数说明,修改之前的代码。代码如下(请注意第6~7行):

  2016年12月18日更新:1、增加同步日志,方便查看失败原因;2、增加了对同步结果的判断,如果失败则不添加自定义列。Ps:请使用下面的最新代码覆盖旧代码。

  /**

* WordPress发布文章同步到新浪微博(带图片&自定义栏目版)

* 文章地址:http://zhangge.net/4947.html

* 最后更新:2016年12月18日

*/

function post_to_sina_weibo($post_ID) {

   /* 鉴于很多朋友反馈发布文章空白,临时加上调试代码,若无问题可删除此行,若有问题请将错误信息在本文留言即可 */

   ini_set(&#x27;display_errors&#x27;, true);

 

   /* 此处修改为通过文章自定义栏目来判断是否同步 */

   if(get_post_meta($post_ID,&#x27;weibo_sync&#x27;,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 == &#x27;publish&#x27; && $_POST[&#x27;original_post_status&#x27;] != &#x27;publish&#x27;) {

       $a*敏*感*词*ey=&#x27;1034947262&#x27;; /* 此处是你的新浪微博a*敏*感*词*ey,不修改的话就会显示来自张戈博客哦! */

       $username=&#x27;微博用户名&#x27;;

       $userpassword=&#x27;微博密码&#x27;;

       $request = new WP_Http;

       $keywords = "";

 

       /* 获取文章标签关键词 */

       $tags = wp_get_post_tags($post_ID);

       foreach ($tags as $tag ) {

          $keywords = $keywords.&#x27;#&#x27;.$tag->name."#";

       }

 

      /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */

     $string1 = &#x27;【文章发布】&#x27; . strip_tags( $get_post_title ).&#x27;:&#x27;;

     $string2 = $keywords.&#x27; 查看全文:&#x27;.get_permalink($post_ID);

 

     /* 微博字数控制,避免超标同步失败 */

      $wb_num = (138 - WeiboLength($string1.$string2))*2;

      $status = $string1.mb_strimwidth(strip_tags( apply_filters(&#x27;the_content&#x27;, $get_post_centent)),0, $wb_num,&#x27;...&#x27;).$string2;

    

       /* 获取特*敏*感*词*片,如果没设置就抓取文章第一张图片 */

       $url = get_mypost_thumbnail($post_ID);

    

       /* 判断是否存在图片,定义不同的接口 */

       if(!empty($url)){

           $api_url = &#x27;https://api.weibo.com/2/statuses/upload_url_text.json&#x27;; /* 新的API接口地址 */

           $body = array(&#x27;status&#x27; => $status,&#x27;source&#x27; => $a*敏*感*词*ey,&#x27;url&#x27; => $url);

       } else {

           $api_url = &#x27;https://api.weibo.com/2/statuses/update.json&#x27;;

           $body = array(&#x27;status&#x27; => $status,&#x27;source&#x27; => $a*敏*感*词*ey);

       }

       $headers = array(&#x27;Authorization&#x27; => &#x27;Basic &#x27; . base64_encode("$username:$userpassword"));

       $results = $request->post($api_url, array(&#x27;body&#x27; => $body,&#x27;headers&#x27; => $headers));

       $result  = $results[&#x27;body&#x27;];

        if(!strstr($result ,&#x27;error_code&#x27;)) {

            // 若成功,则给新增自定义栏目weibo_sync,避免以后更新文章重复同步

            add_post_meta($post_ID, &#x27;weibo_sync&#x27;, 1, true);

        } else {

            // 若失败,则记录错误日志

            logInfo($result);

        }  

       add_post_meta($post_ID, &#x27;weibo_sync&#x27;, 1, true);

    }

}

add_action(&#x27;publish_post&#x27;, &#x27;post_to_sina_weibo&#x27;, 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 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(&#x27;get_mypost_thumbnail&#x27;)){

  function get_mypost_thumbnail($post_ID){

     if (has_post_thumbnail()) {

            $timthumb_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), &#x27;full&#x27; );

            $url = $timthumb_src[0];

    } else {

        if(!$post_content){

            $post = get_post($post_ID);

            $post_content = $post->post_content;

        }

        preg_match_all(&#x27;||i&#x27;, do_shortcode($post_content), $matches);

        if( $matches && isset($matches[1]) && isset($matches[1][0]) ){      

            $url =  $matches[1][0];

        }else{

            $url =  &#x27;&#x27;;

        }

    }

    return $url;

  }

}

 

//写日志函数

function logInfo($msg)

{

    $logSwitch  = 1;                     // 日志开关:1表示打开,0表示关闭

    $logFile    = &#x27;/tmp/sync_weibo.log&#x27;; // 日志路径          

    if ($logSwitch == 0 ) return;

    date_default_timezone_set(&#x27;Asia/Shanghai&#x27;);

    file_put_contents($logFile, date(&#x27;[Y-m-d H:i:s]: &#x27;) . $msg . PHP_EOL, FILE_APPEND);

    return $msg;

}

  三、权限申请

  万事俱备,但是发布文章肯定不会同步,为什么呢?因为我没有权限~!原来这个接口需要在原有的基础上额外应用。

  如果你的网站已经在微博申请访问权限,点击应用名称即可:

  然后,在界面管理==&gt;申请权限==&gt;申请微博的高级写权限:

  无论多么容易,门槛多么低,我们在问别人的时候都要保持真诚的态度:

  一般1个工作日内即可过关:

  通过后可以发布文章,可以看到效果,不仅有特*敏*感*词*片,还有显示【来自XX博客】:

  它是否再次满足了您的迫切需求?哈哈!

  2016年1月16日新增内容:我们最近发现了一个微博同步失败的原因,分享了微博同步失败的终极DeBUG方法。详情请见:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线