最新消息:

WordPress 文章同步到新浪微博

很多小伙伴们都在问我是如何实现文章同步新浪微博的,其实是参考了 张戈博客 的思路,具体的权限申请与操作方法,他也介绍的很清楚,小伙伴们可以细细品读。接下来我要分享出我的代码,大家可以比较一下。

复制以下代码到当前使用主题的 functions.php 文件中即可。

/*
 功能描述: 文章同步到新浪微博
 功能介绍页面: https://www.ivicos.com/46.html
*/
function post_to_sina_weibo($post_ID) {
 if( get_post_meta($post_ID,'weibo_sync',true) == 1 ) return;
 $username = "xxxxxx"; //你的微博登录用户名
 $password = "xxxxxx"; //你的微博登陆密码
 $source = "xxxxxx"; //你的新浪微博 appkey
 $get_post_info = get_post($post_ID);
 if ( $get_post_info->post_status == 'publish' && $_POST['original_post_status'] != 'publish' ) {
 $request = new WP_Http;
 $status = '【' . strip_tags( $_POST['post_title'] ) . '】 ' . mb_strimwidth(strip_tags(apply_filters('the_content', $_POST['post_content'])) , 0, 120, ' ... ') . ' 全文阅读:' . get_permalink($post_ID);
 if(preg_match('/<img.+src=\"?(.+\.(jpg|gif|bmp|bnp|png))\"?.+>/i',$_POST['post_content'],$match)) { //当文章中有图片抓取第一张,前提是有微博高级写入权限
 $url = preg_replace('/["]+/i','',$match[1]);
 $api_url = 'https://api.weibo.com/2/statuses/upload_url_text.json';
 $body = array( 'status' => $status,'url' => stripslashes($url), 'source'=> $source );
 }
 else { //文章中如果没有图片
 $api_url = 'https://api.weibo.com/2/statuses/update.json';
 $body = array( 'status' => $status, 'source'=> $source );
 }
 $headers = array( 'Authorization' => 'Basic ' . base64_encode("$username:$password") );
 $result = $request->post( $api_url , array( 'body' => $body, 'headers' => $headers ) );
 add_post_meta($post_ID, 'weibo_sync', 1, true); //同步成功,则给新增自定义栏目 weibo_sync,避免以后更新文章重复同步
 }
}
add_action('publish_post', 'post_to_sina_weibo', 0);

以上代码只是用文章中的图片来做为特色图,如果你想用缩略图作为特色图片,请将上述代码中的 14、15 行代码改为:

if( has_post_thumbnail() ) {
 $timthumb_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_ID), 'full' ); 
 $url = $timthumb_src[0];

如果向两者兼得,建议直接使用 张戈博客 的代码,或者你也可以自行研究出更好的办法。

好了,Wordpress 文章同步到新浪微博 这个方法就分享到这里,非常感谢你的来访。如果你很喜欢本站,请不要忘记收藏本站,以便下次继续访问;也可以 关注站长微博 随时获取最新动态。你的支持就是我最大的动力!

转载请注明:爱维科斯 » WordPress 文章同步到新浪微博

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者