wordpress對接微博使wordpress文章同步到微博
WordPress文章發布后無插件自動同步到新浪微博詳細步驟:
1、申請新浪微博APPKEY
申請地址:http://open.weibo.com/
我們需要有自己的新浪微博賬戶,然后登陸上面的地址,申請APPKEY。
(1)申請網站接入
(2)按照下圖流程進行操作:
(3)網站接入完成后,在我的應用下面會看到自己剛接入的網站,這個時候我們需要記下如下圖位置處的App Key
2、修改wordpress代碼
在當前使用的主題根目錄下的functions.php中加入如下代碼:
function?post_to_sina_weibo($post_ID)?{ ???/*?此處修改為通過文章自定義欄目來判斷是否同步?*/ ???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='上個步驟獲取的App?key';?? ???????$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?{ preg_match_all('/@@##@@/sim',?$get_post_centent, $strResult,?PREG_PATTERN_ORDER);??//正則獲取文章中第一張圖片 $n?=?count($strResult[1]);?? if($n?>?0){ $url=$strResult[1][0];?? } } ???/*?判斷是否存在圖片,定義不同的接口?*/ ???????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??0){ ????????????if(ord(substr($tempaddtext,$cind,1))?<p>至此我們只要修改上述代碼中的三處,其中APP KEY直接修改成我們自己的APP KEY,然后輸入自己的微博賬戶和密碼。</p><p>更多wordpress相關技術文章,請訪問<a href="https://www.php.cn/cms/wordpress/" target="_blank">wordpress教程</a>欄目進行學習!</p><img . alt="wordpress如何對接微博使文章同步" ></img.>
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END