腾讯云服务器优惠活动华纳云香港服务器

纯代码实现WordPress文章同步到微博头条文章

WordPress主题推荐

昨天推荐『WordPress 文章同步到新浪微博普通和头条文章插件』就说到 boke112 导航结合祭夜 blog 分享的《[API 使用代码]WordPress 自动同步到新浪微博头条文章》和张戈博客分享的『WordPress 发布文章自动同步到新浪微博(带特色图片)』试着折腾了一下,目前已经成功实现 WordPress 站点发布文章可勾选是否同步到新浪微博头条文章。同步到头条文章的效果如下(或关注):

纯代码实现WordPress文章同步到微博头条文章-第1张-boke112百科(boke112.com)

温馨提示:想要实现 WordPress 站点文章自动同步到微博头条文章,需要拥有应用 appkey 和头条文章高级写入接口权限,两者都成功申请之后再往下折腾会比较好。

有些站长不喜欢插件实现,所以就问到我是否可以分享实现 WordPress 文章同步到微博头条文章的代码。其实根据祭夜 blog 分享的代码就已经满足要求了,下面先贴出他所分享的代码:

/** 
* WordPress 同步文章到新浪微博头条文章 By 无主题博客 
* 完善修正 By 祭夜
* 修正内容:
* 1.部分代码错误
* 2.修复同步到头条文章时 HTML 代码被去掉的问题
* 3.增加头条文章封面
* 4.添加博客文章的标签关联到新浪话题
* 原文地址: http://wuzhuti.cn/2715.html(原站已停运)
*/ 
function post_to_sina_weibo_toutiao($post_ID) { 
//ini_set('display_errors', true);
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 = 'App Key'; //App Key
$username = '用户名'; //用户名
$userpassword = '密码'; //密码
$request = new WP_Http; 
/* 获取文章标签关键词*/
$tags = wp_get_post_tags($post_ID);
foreach ($tags as $tag ) {
$keywords = $keywords.'#'.$tag->name."#";
} 
$status = '【' . strip_tags($get_post_title) . '】 ' . mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 132, ' '); 
$api_url = 'https://api.weibo.com/proxy/article/publish.json'; 
$body = array(
'title' => strip_tags($get_post_title), //头条的标题
'content' => get_post($post_ID)->post_content.' 
原文地址:' . get_permalink($post_ID), //头条的正文
'cover' => mmimg($post_ID), //头条的封面
'summary' => mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 110, '...'), //头条的导语
'text' => mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 110, $status).$keywords.'原文地址:' . get_permalink($post_ID), //微博的内容
'source' => $appkey
); 
$headers = array('Authorization' => 'Basic ' . base64_encode("$username:$userpassword")); 
$result = $request->post($api_url, array('body' => $body,'headers' => $headers)); 
logInfo($result['body']);
} 
} 
add_action('publish_post', 'post_to_sina_weibo_toutiao', 0); //给发布文章增加一个分享微博头条文章的动作
//获取封面
function catch_that_image($postID){
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',get_post($postID)->post_content,$matches);
$first_img = $matches[1][0];
//将文章第一张图片的地址赋值给$first_img
if(empty($first_img)){
//文章第一张图为空,也就是整篇文章没有图片,将默认设置的图片的地址赋值给$first_img
$popimg = git_get_option('git_sina_weibo_cover');
$first_img = $popimg;
}
return $first_img;
}
function mmimg($postID){
$cti = catch_that_image($postID);
//得到$first_img 的值,并赋值给$cti
$showimg = $cti;
//将$cti 的值赋值给$showimg
has_post_thumbnail();
if(has_post_thumbnail()){
//判断是否有特色图片,有则将$showimg 的值替换为特色图片的地址,否则不变
$thumbnail_image_url = wp_get_attachment_image_src(get_post_thumbnail_id(),'thumbnail');
$shareimg = $thumbnail_image_url[0];
}
else{
$shareimg = $showimg;
}
;
return $shareimg;
}
//调用代码:mmimg($post_ID)
//写日志函数
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;
}

说明:以上代码必须修改:19,20,21,55 行。建议修改:72 行(正常使用请关闭,异常时请打开)。以上有些代码对方是从主题选项中获取,比如第 55 行,所以建议大家在使用代码的时候检查仔细,把比较个性化的代码改为适合自己使用的代码,并不是直接复制粘贴就能使用哦。

以上代码来自@祭夜 blog 《[API 使用代码]WordPress 自动同步到新浪微博头条文章

boke112 导航是根据自己的实际情况,在以上代码的基础上增加了一个开关,即是在编辑文章的时候勾选“推送”后才会推送到微博头条,毕竟不是每一篇文章都适合推送的。具体见下图:

纯代码实现WordPress文章同步到微博头条文章-第2张-boke112百科(boke112.com)

boke112 导航目前使用的发布文章自动推送到新浪微博头条文章的代码如下:

/**
* 纯代码实现 WordPress 文章同步到微博头条文章
*/

//同步选项代码
add_action( 'admin_menu', 'weibo_submit_create' );
function weibo_submit_create(){
add_action( 'post_submitbox_misc_actions', 'weibo_submit_to_publish_metabox' );
}

//同步选项
function weibo_submit_to_publish_metabox() {
global $post_ID;
$checked_o = (get_post_meta($post_ID,'weibott',true)==1) ? 'disabled checked="checked"' : '';
echo '<div class="misc-pub-section misc-pub-post-status"><input name="xiong_Submit_CHECK" type="hidden" value="true">是否推送微博头条:<span id="submit-span"><label><input name="weibott" type="checkbox" value="1" '.$checked_o.'>推送</label></span></div>';
}

//文章保存时更新原创字段
if(!function_exists('weibo_toutiao')){
function weibo_toutiao($post_ID) {
global $post_ID;
if(get_post_meta($post_ID, 'weibott', true) == 1) return;
if($_POST['weibott']=='1'){add_post_meta($post_ID, 'weibott', 1, true);} 
}
add_action('save_post', 'weibo_toutiao', 0);
}

/**
* WordPress 发布文章同步到新浪微博头条
*/
function post_to_sina_weibo($post_ID) { 
/* 此处修改为通过文章自定义栏目来判断是否同步 */
if(get_post_meta($post_ID,'weibo_sync',true) == 1) return;
if((!get_post_meta($post_ID, 'weibott', true))&& $_POST['weibott']=='1'){add_post_meta($post_ID, 'weibott', 1, true);}
$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_meta($post_ID, 'weibott', true) == 1 && $get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish') {
$appkey = '123456789'; 
$username = '[email protected]';
$userpassword = '123456789';
$request = new WP_Http;
$string1 = '发布了头条文章:《'. strip_tags( $get_post_title ).'》';
$string2 = ' 原文地址:'.get_permalink($post_ID);
$wb_num = (108 - 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/proxy/article/publish.json';
$body = array(
'title' => strip_tags($get_post_title),
'content' => get_post($post_ID)->post_content.' 
原文地址:' . get_permalink($post_ID),
'cover' => catch_images($post_ID),//头条封面
'summary' => mb_strimwidth(strip_tags(apply_filters('the_content', $get_post_centent)) , 0, 110, '...'),
'text' => $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;
}

//获取微博头条封面
function catch_images($post_ID) {
$post=get_post($post_ID);
$first_img = '';
if ( get_post_meta($post->ID, 'wzshow', true) ) {
$first_img = get_post_meta($post->ID, 'wzshow', true);
}else{
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
}
if(empty($first_img)){ //Defines a default image
$random = mt_rand(1, 10);
echo get_bloginfo ( 'stylesheet_directory' );
echo '/images/random/r'.$random.'.png';
}
return $first_img;
}

代码说明:

1. 第 39~41 行代码请修改为自己的。

2. 第 109~127 行代码是头条文章封面图,默认获取指定缩略图,没有就获取文章第一张图片,也没有就获取随机图片,建议大家根据自己所使用的主题进行修改,或者直接删除第 109~127 行代码并将第 52 行代码中的 catch_images($post_ID)改为自己主题的缩略图函数。

3. 第 43~46 行代码是同步头条文章时发布到新浪微博的代码,可根据自己站点情况修改,默认是 boke112 导航当前使用的格式,具体可以加 boke112 导航微博(传送门)看效果图,或看本文第一张图片。

4. 第 63 行代码意思就是 post 类型的文章发布时自动同步到头条文章,如果你的 WordPress 站点还有其他自定义类型(如 gonggao),那么就自行在它的下方添加以下代码即可:

add_action('publish_gonggao', 'post_to_sina_weibo', 0);

目前,boke112 导航使用以上代码实现同步到新浪微博头条文章的功能已经持续今天,不管是直接发布的文章还是定时发布的文章,只要在编辑文章时勾选了“推送”到头条文章的,都能成功推送。如果遇到不能推送的,请检查看看 appkey、微博登录用户名和密码是否填写正确,头条文章封面代码是否修改正确等。

本文地址:https://boke112.com/post/7007.html

赞 (5) 打赏
版权声明:本文为原创文章,版权归 boke112百科 所有,欢迎分享本文,转载请保留出处!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu