前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WordPress发布文章自动同步到新浪微博(带特色图片)

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

作者头像
WindCoder
发布2018-09-19 18:10:35
2.7K1
发布2018-09-19 18:10:35
举报
文章被收录于专栏:WindCoderWindCoder

整体来源于张戈博客,本处仅是修改添加了一处显示文章分类的小功能,若是一篇文章有多个分类,默认使用第一个。经测试好像对于七牛中设置了空间防盗链的不太友好,可能会报2007错误。

方法

1、在微博开放平台创建网站接入的应用。

小提示:境外网站可以使用 ping结果加站长综合查询中ip部分的截图作为证明哦。

2、申请通过后,在接口管理-》申请接口,选中“微博高级写入接口”

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

在下面申请理由中,填写如下信息,提交申请后大概一个工作日即可通过。

希望在微博同步中插入特色图片,特申请微博高级写入权限,望批准,感谢~~

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

3、通过后,修改如下代码中的App Key以及微博账号密码,然后将代码放入functions.php文件中即可。

代码

代码语言:javascript
复制
/**
* WordPress发布文章同步到新浪微博(带图片&自定义栏目版)
* 文章地址:http://zhangge.net/4947.html
*/
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."#";
       }

      /* 修改了下风格,并添加文章关键词作为微博话题,提高与其他相关微博的关联率 */
     $get_post_category_weiboname =get_the_category($post_ID)[0]->cat_name;
     $string1 = '【'.$get_post_category_weiboname.'】' . 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"));
       $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 获取文章图片加强版 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;
  }
}

测试结果

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

课外总结

get_the_category(获取分类相关内容)

说明

如要查看一些说明,请点击http://www.favortt.com/wordpress-functions-class

描述

模板标签函数用来返回的值是一个数组形式的对象,返回的内容是文章下分类信息,可以在文章主循环外使用(Loop)

用法
代码语言:javascript
复制
<?php get_the_category( $id ) ?>
参数说明

$id(可选)文章的ID编号,默认值为$post->ID (当前文章的ID编号)。

返回值

cat_ID

分类ID编号 (也可以保存为 ‘term_id’)

cat_name

类别名称 (也可以保存为 ‘name’)

category_nicename

类分类名称产生的一个slug (也可以保存为’slug’)

category_描述

分类描述 (也保存为’description’)

category_parent

当前分类的父类别的ID编号。’0′ 表示没有父类别。(同样也可以保存为 ‘parent’)

category_count

该分类有多少文章 (也可以保存为 ‘count’)

示例
显示第一个分类名称
代码语言:javascript
复制
<?php

  $category = get_the_category();

  echo $category[0]->cat_name;

?>
显示多个分类名称(当一个篇文章有多个分类的时候)
代码语言:javascript
复制
<?php
$cat = get_the_category();

foreach($cat as $key=>$category)
{
    echo $category->cat_name.'<br/>';
}

?>
显示分类的所有内容
代码语言:javascript
复制
	<?php
	&nbsp;$categories = get_the_category();
	&nbsp;&nbsp;
	&nbsp;var_dump($categories);
	?>
	//显示的内容就是上面提到的返回值

通过上面的方法我们就可以在文章的循环外获取分类的内容,这样我们就可以用在很多的功能中,比如可以在每篇文章下面添加一个相关文章列表

附录

错误及解决方案

改为https后一直出错,最开始报如下错误:

最初错误

\"error\":\"does multipart has image?\",\"error_code\":20007

感觉可能和防盗链名单有关,将微博的相关链接填到白名单后,又开始报如下错误:

之后错误

cURL error 60: SSL certificate problem: certificate has expired

记得之前看张戈博客时看到一篇他遇到问题的解决方案,就上去看了下,发现里面解决https的方法是把图片链接的https替换成http,抱着试一试的态度,竟然成功了,添加的代码如下:

代码语言:javascript
复制
$url = preg_replace('/https:\/\//i','http://',$url);

参考资料: WordPress发布文章同步到新浪微博失败的问题解决与分享

参考资料

get_the_category(获取分类相关内容)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方法
    • 代码
      • 测试结果
      • 课外总结
        • get_the_category(获取分类相关内容)
          • 说明
          • 描述
          • 用法
          • 参数说明
          • 返回值
          • 示例
          • 显示分类的所有内容
      • 附录
        • 错误及解决方案
          • 最初错误
          • 之后错误
          • 参考资料
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档