转载:WordPress发布文章带图自动同步到新浪微博

流年
流年
管理员
327
文章
500.1千
浏览
71,534字数 1101阅读3分40秒

先分享不带图片的代码,代码添加以下代码到主题函数文件里functions.php

  1. // 微博同步
  2. function post_to_sina_weibo($post_ID) {
  3.  if( wp_is_post_revision($post_ID) ) return;
  4. $get_post_info = get_post($post_ID);
  5. $get_post_centent = get_post($post_ID)->post_content;
  6. $get_post_title = get_post($post_ID)->post_title;
  7.  if ( $get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish' ) {
  8. $request = new WP_Http;
  9. $status = '【' . strip_tags$get_post_title ) . '】 ' . mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, 132,'...') . ' 全文地址:' . get_permalink($post_ID) ;
  10. $api_url = 'https://api.weibo.com/2/statuses/update.json';
  11. $body = array( 'status' => $status, 'source'=>'3332014706');/*3332014706指的是Key是本站的,如果你没申请就直接用这个也可以*/
  12. $headers = array( 'Authorization' => 'Basic ' . 'bGluZ2h1eGlhb3FpQHNpbmEuYtOnh1aGFuMwMA==' );
  13.         /*
  14.         bGluZ2h1eGlhb3FpQHNpbmEuYtOnh1aGFuMwMA==指的是登录新浪微博的用户名和密码,你自己到http://www.mxcz.net/tools/base64.aspx把你的帐号密码进行一下加密,格式是(username@gmail.com:password)
  15.         */
  16. $result = $request->post( $api_url , array( 'body' => $body, 'headers' => $headers ) );
  17.  }
  18. }
  19. add_action('publish_post', 'post_to_sina_weibo', 0);

有同步功能还是很方便的,代码具体在那挖来的我也忘记了,但是以下代码确实是挺好用的,因为一般的同步假如文章修改了还是会同步到微博,这代码就不会,具体效果
转载:WordPress发布文章带图自动同步到新浪微博
想要同步的效果,那么就必须去新浪微博开发者平台去申请个appkey,然后还要去申请个高级写入
转载:WordPress发布文章带图自动同步到新浪微博
都申请完成后就可以添加以下代码到主题函数文件里functions.php

  1. /**
  2. * WordPress发布文章同步到新浪微博(带图片&自定义栏目版)
  3. * 文章地址:http://www.blogba.cn/sync-wordpress-with-automatic-figure-to-sina-weibo.html
  4. */
  5. function post_to_sina_weibo($post_ID) {
  6.    /* 鉴于很多朋友反馈发布文章空白,临时加上调试代码,若无问题可删除此行,若有问题请将错误信息在本文留言即可 */
  7.    ini_set('display_errors', true);
  8.    /* 此处修改为通过文章自定义栏目来判断是否同步 */
  9.    if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;
  10.    $get_post_info = get_post($post_ID);
  11.    $get_post_centent = get_post($post_ID)->post_content;
  12.    $get_post_title = get_post($post_ID)->post_title;
  13.    if ($get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
  14.        $appkey='3332014706'; /* 此处是你的新浪微博appkey,不修改的话就会显示来自极客自留地哦! */
  15.        $username='微博用户名';
  16.        $userpassword='微博密码';
  17.        $request = new WP_Http;
  18.        $keywords = "";
  19.        /* 获取文章标签关键词 */
  20.        $tags = wp_get_post_tags($post_ID);
  21.        foreach ($tags as $tag ) {
  22.           $keywords = $keywords.'#'.$tag->name."#";
  23.        }
  24.       /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */
  25.      $string1 = '【文章发布】' . strip_tags$get_post_title ).':';
  26.      $string2 = $keywords.' 查看全文:'.get_permalink($post_ID);
  27.      /* 微博字数控制,避免超标同步失败 */
  28.      $wb_num = (138 - WeiboLength($string1.$string2))*2;
  29.      $status = $string1.mb_strimwidth(strip_tags( apply_filters('the_content', $get_post_centent)),0, $wb_num,'...').$string2;
  30.        /* 获取特色图片,如果没设置就抓取文章第一张图片 */
  31.        if (has_post_thumbnail()) {
  32.           $timthumb_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'full' );
  33.           $url = $timthumb_src[0];
  34.        /* 抓取第一张图片作为特色图片,需要主题函数支持 */
  35.        } else if(function_exists('catch_first_image')) {
  36.           $url = catch_first_image();
  37.        }
  38.        /* 判断是否存在图片,定义不同的接口 */
  39.        if(!emptyempty($url)){
  40.            $api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json'; /* 新的API接口地址 */
  41.            $body = array('status' => $status,'source' => $appkey,'url' => $url);
  42.        } else {
  43.            $api_url = 'https://api.weibo.com/2/statuses/update.json';
  44.            $body = array('status' => $status,'source' => $appkey);
  45.        }
  46.        $headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword"));
  47.        $result = $request->post($api_urlarray('body' => $body,'headers' => $headers));
  48.        /* 若同步成功,则给新增自定义栏目weibo_sync,避免以后更新文章重复同步 */
  49.        add_post_meta($post_ID, 'weibo_sync', 1, true);
  50.     }
  51. }
  52. add_action('publish_post', 'post_to_sina_weibo', 0);
  53. /*
  54. //获取微博字符长度函数 
  55. */
  56. function WeiboLength($str)
  57. {
  58.     $arr = arr_split_zh($str);   //先将字符串分割到数组中
  59.     foreach ($arr as $v){
  60.         $temp = ord($v);        //转换为ASCII码
  61.         if ($temp > 0 && $temp < 127) {
  62.             $len = $len+0.5;
  63.         }else{
  64.             $len ++;
  65.         }
  66.     }
  67.     return ceil($len);        //加一取整
  68. }
  69. /*
  70. //拆分字符串函数,只支持 gb2312编码  
  71. //参考:http://u-czh.iteye.com/blog/1565858
  72. */
  73. function arr_split_zh($tempaddtext){
  74.     $tempaddtext = iconv("UTF-8""GBK//IGNORE"$tempaddtext);
  75.     $cind = 0;
  76.     $arr_cont=array();
  77.     for($i=0;$i<strlen($tempaddtext);$i++)
  78.     {
  79.         if(strlen(substr($tempaddtext,$cind,1)) > 0){
  80.             if(ord(substr($tempaddtext,$cind,1)) < 0xA1 ){ //如果为英文则取1个字节
  81.                 array_push($arr_cont,substr($tempaddtext,$cind,1));
  82.                 $cind++;
  83.             }else{
  84.                 array_push($arr_cont,substr($tempaddtext,$cind,2));
  85.                 $cind+=2;
  86.             }
  87.         }
  88.     }
  89.     foreach ($arr_cont as &$row)
  90.     {
  91.         $row=iconv("gb2312","UTF-8",$row);
  92.     }
  93.     return $arr_cont;
  94. }

 

本文转载至:极客自留地

网站最后更新:2026-1-13
流年
  • 本文由 流年 发表于2015年11月22日 07:56:44
  • 除非特殊声明,本站文章均为原创,需要转载,请留言说明!
评论  7  访客  4  作者  3
    • 早莫
      早莫 0

      定时发布时,如果文章的固定链接设置成:分类ID+文章ID的话,同步到微博的链接就成了文章ID了,分类ID丢失了,这个怎么解决呢

      • 斯文败类
        斯文败类 1

        我是代码盲,想弄又不会折腾

        • 流年
          流年

          测试

          • 武动青春
            武动青春 2

            啦啦。。

            • 流年
              流年

              :shock:

            匿名

            发表评论

            匿名网友
            确定

            拖动滑块以完成验证