wordpress文章自动同步新浪微博

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 = ‘微博给你的 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;
/* 获取特色图片,如果没设置就抓取文章第一张图片 */
if (has_post_thumbnail()) {
$timthumb_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_ID) , ‘full’);
$url = $timthumb_src[0];
/* 抓取第一张图片作为特色图片,需要主题函数支持 */
} else {
global $post, $posts;
$first_img1 = ”;
ob_start();
ob_end_clean();
preg_match_all(‘/<img.+src=[\'”]([^\'”]+)[\'”].*>/i’, $get_post_centent, $matches);
$first_img1 = $matches[1][0];
if ($first_img1 != “” || $first_img1 != null) {
$url = $first_img1;
} else {
$url = “http://tp1.sinaimg.cn/2216528420/180/22871427629/1”;
}
}
/* 判断是否存在图片,定义不同的接口 */
if (!empty($url)) {
$api_url = ‘https://api.weibo.com/2/statuses/upload_url_text.json’; /* 新的API接口地址 */
$body = array(
‘source’ => $appkey,
‘status’ => $status,
‘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);

未经允许不得转载:前端撸码笔记 » wordpress文章自动同步新浪微博

上一篇:

下一篇: