WordPress文章同步微博实现方法 – 无插件脚本同步微博

我们有些朋友希望更新在WordPress博客的文章能够同步到微博中。这里我们可能看到有一些插件可以实现,这里麦子在整理电脑文档的时候看到有这么一个脚本,应该是之前一个网友给我的,可以同步到微博中。如果我们有需要可以试试。这里,麦子后面也准备试试。

WordPress文章同步微博实现方法 - 无插件脚本同步微博

我们需要先到微博中申请TOKEN:https://open.weibo.com/tools/console

然后我们将API信息修改下面的脚本,然后添加到我们的主题 Functions.php 文件中。

//同步微博 cnwper.com收藏
add_action('publish_post', 'new_post_weibo', 1);
function new_post_weibo($post_ID, $debug = false) {
	global $post;
	if (!wp_is_post_revision($post_ID) && $post->post_status != "publish" || $debug == true){
		if (isset($post) && $post->post_type != "post") return;
		$access_token = "2.00xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
		$headers = array();
		$headers[] = "Authorization: OAuth2 ".$access_token;
		$url = 'https://api.weibo.com/2/statuses/share.json';
        $status =  "WordPress建站笔记更新《".strip_tags( $_POST['post_title'] ) .'》'.mb_strimwidth(strip_tags(apply_filters('the_content',$_POST['post_content'])),0,85,".")."(文章原文来自cnwper.com)→".get_permalink($post_ID);
		if (has_post_thumbnail()) {
			$post_thumbnail_id = wp_get_attachment_scr(get_post_thumbnail_id($post->ID));
			$img_src = $post_thumbnail_id;
		}else{
             $img_src= '';
			$content = get_post( $post_ID )->post_content;
            preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $strResult);

			$img_src = $strResult [1] [0];
		}

		if(!empty($img_src)) {
			$picfile = str_replace(home_url(),$_SERVER["DOCUMENT_ROOT"],$img_src);
			if(!empty($picfile)){
				$filecontent = file_get_contents($picfile);
			}else{
				$filecontent = file_get_contents($img_src);
			}
			$array = explode('?', basename($img_src));
			$filename = $array[0];
			$boundary = uniqid('------------------');
			$MPboundary = '--'.$boundary;
			$endMPboundary = $MPboundary. '--';
			$multipartbody = '';
			$multipartbody .= $MPboundary . "\r\n";
			$multipartbody .= 'Content-Disposition: form-data; name="pic"; filename="' . $filename . '"' . "\r\n";
			$multipartbody .= "Content-Type: image/unknown\r\n\r\n";
			$multipartbody .= $filecontent. "\r\n";
			$multipartbody .= $MPboundary . "\r\n";
			$multipartbody .= 'content-disposition: form-data; name="status' . "\"\r\n\r\n";
			$multipartbody .= urlencode($status)."\r\n";
			$multipartbody .= $endMPboundary;
			$headers[] = "Content-Type: multipart/form-data; boundary=" . $boundary;
			$data = $multipartbody;
		}else{
			$data = "status=" . urlencode($status);
		}
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
		$curlResponse = curl_exec($ch);
		curl_close($ch);
		$output = json_decode($curlResponse);
		if($debug){
			var_dump($output);
			echo '<hr />';
			var_dump($data);
		}
	}
}

我们可以试试是否同步,正常是会同步摘要、连接和图片的。

投票 post
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享