HTML,CSS,PHP,ワードプレスカスタマイズ 技術情報資料

アイキャッチの自動挿入

アイキャッチの自動挿入が欲しかった。
最新ソース

テスト用画像(楽天アフィリリンクタグ)


量産用のアフィリエイト記事を書くときアフィリリンク画像をいちいちダウンロードするのが面倒。
ってことで、探すと通常は、Auto Post Thumbnail にたどり着く。

でもね、でもさ、Auto Post Thumbnail って書いておいて、アイキャッチ取り込み~~って一括処理なんよ。
ね?面倒くせーべ?したら、記事作ったらプレビューして画像ダウンロードした方が早いってばよ。

んで、探していたら、こちらにたどり着きました。感謝(-人-
http://nelog.jp/auto-post-thumbnail-custum

プラグインには、なっていないんだけど、function.php にペタと張り付ければオケ。
が・・・当然のことながら、楽天のタグは、そのままでは取り込めない。

それともう一つ、ワードプレスのファイルシステムに対応している。
そのためか知らないけど、画像読み込みできない。

散々しらべたんだけど、ファイルシステムそのものを使おうとおもった時点でおかしい。
もう少し大人になってからにしようとおもって Auto Post Thumbnail のパーツをそのまま持ってきた。

寝ログさんからの変更点は、以下の通り。
・楽天の画像タグに対応。
・ファイルシステムを Auto Post Thumbnail のものを使用。

んで、寝ログさんのパーツでいいのは、ユーチューブのサムネイルでもオケってこと。
逆にこのパーツを Auto Post Thumbnail に入れてあげるのもナイスなアイディアだとおもう。
あちしは、ヤフショ、アマゾンのリンクタグもひろえるようになったら、Auto Post Thumbnail に書き戻そうかと思ってる。


以下がソースです。これをそのままペタッと function.php に張り込めばオケ。
記事を投稿した時点でアイキャッチを自動挿入します。
※ Auto Post Thumbnail そのものがファイルシステムを使ってないので、そこのところはご理解ください。
※ 楽天タグの判断に ?pc のみで判断しているので、場合によっては、あれ?ってなるかもしれないので注意。
  使い込んで、ここんところは、もっと正確な情報で拾うようにしてくださいませ。
  あちしも随時書き換えていきますが。ヤフーショッピングとかにも対応させたいし。

/////////////////////////////////////////////
//コピペ一発でWordpressの投稿時にアイキャッチを自動設定するカスタマイズ方法(YouTube対応版)
//http://nelog.jp/auto-post-thumbnail-custum
//楽天イメージタグ対応
//http://tecinfo.yuzumaru.co.jp/wp/
/////////////////////////////////////////////

//WP_Filesystemの利用
require_once(ABSPATH . '/wp-admin/includes/image.php');
//イメージファイルがサーバー内にない場合は取得する
function fetch_thumbnail_image($matches, $key, $post_content, $post_id){
	//正しいタイトルをイメージに割り当てる。IMGタグから抽出
	$imageTitle = '';
	preg_match_all('/<\s*img [^\>]*title\s*=\s*[\""\']?([^\""\'>]*)/i', $post_content, $matchesTitle);

	if (count($matchesTitle) && isset($matchesTitle[1])) {
		$imageTitle = $matchesTitle[1][$key];
	}

	//処理のためのURL取得
	$imageUrl = $matches[1][$key];

	//楽天イメージタグの処理
	$p=strpos($imageUrl,'?pc');
	if($p>0){
		$imgWork=mb_substr($imageUrl,$p);
		$imgWork=urldecode($imgWork);
		$p=strpos($imgWork,'=');
		if($p>0){
			$imgWork=mb_substr($imgWork,$p+1);
			$p=strpos($imgWork,'?');
			if($p>0){
				$imageUrl=mb_substr($imgWork,0,$p);
			}
		}
	}

	//ファイル名の取得
	$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);

	if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])){
		return null;
	}
	//ユニック(一意)ファイル名を生成
	$filename = wp_unique_filename( $uploads['path'], $filename );
	//ファイルをアップロードディレクトリに移動
	$new_file = $uploads['path'] . "/$filename";
	if (!ini_get('allow_url_fopen')) {
		$file_data = curl_get_file_contents($imageUrl);
	} else {
		$file_data = @file_get_contents($imageUrl);
	}

	if (!$file_data) {
		return null;
	}

	file_put_contents($new_file, $file_data);

	//ファイルのパーミッションを正しく設定
	$stat = stat( dirname( $new_file ));
	$perms = $stat['mode'] & 0000666;
	@ chmod( $new_file, $perms );

	//ファイルタイプの取得。サムネイルにそれを利用
	$wp_filetype = wp_check_filetype( $filename, $mimes );

	extract( $wp_filetype );

	//ファイルタイプがない場合、これ以上進めない
	if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) {
		return null;
	}

	//URLを作成
	$url = $uploads['url'] . "/$filename";

	//添付(attachment)配列を構成
	$attachment = array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => null,
		'post_title' => $imageTitle,
		'post_content' => '',
	);

	$thumb_id = wp_insert_attachment($attachment, $file, $post_id);
	if ( !is_wp_error($thumb_id) ) {
    	//attachmentのアップデート
		wp_update_attachment_metadata( $thumb_id, wp_generate_attachment_metadata( $thumb_id, $new_file ) );
		update_attached_file( $thumb_id, $new_file );
	
    	return $thumb_id;
	}
	
	return null;
}

//投稿内の最初の画像をアイキャッチに設定する(Auto Post Thumnailプラグイン的な機能)
function auto_post_thumbnail_image() {
	global $wpdb;
	global $post;
	$post_id = $post->ID;

	//アイキャッチが既に設定されているかチェック
	if (get_post_meta($post_id, '_thumbnail_id', true) || get_post_meta($post_id, 'skip_post_thumb', true)) {
		return;
	}

	$post = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE id = $post_id");

	//正規表現にマッチしたイメージのリストを格納する変数の初期化
	$matches = array();

	//投稿本文からすべての画像を取得
	preg_match_all('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i', $post[0]->post_content, $matches);
	//YouTubeのサムネイルを取得(画像がなかった場合)
	if (empty($matches[0])) {
		preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $post[0]->post_content, $match);
		if (!empty($match[1])) {
			$matches=array(); $matches[0]=$matches[1]=array('http://img.youtube.com/vi/'.$match[1].'/mqdefault.jpg');
		}
	}

	if (count($matches)) {
		foreach ($matches[0] as $key => $image) {
			//画像がイメージギャラリーにあったなら、サムネイルIDをCSSクラスに追加(イメージタグからIDを探す)
			preg_match('/wp-image-([\d]*)/i', $image, $thumb_id);
			$thumb_id = $thumb_id[1];
		
			//サムネイルが見つからなかったら、データベースから探す
			if (!$thumb_id) {
				$image = substr($image, strpos($image, '"')+1);
				$result = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE guid = '".$image."'");
				$thumb_id = $result[0]->ID;
			}

			//それでもサムネイルIDが見つからなかったら、画像をURLから取得する
			if (!$thumb_id) {
				$thumb_id = fetch_thumbnail_image($matches, $key, $post[0]->post_content, $post_id);
			}
		
			//サムネイルの取得に成功したらPost Metaをアップデート
			if ($thumb_id) {
				update_post_meta( $post_id, '_thumbnail_id', $thumb_id );
				break;
			}
		}
	}
}
//新しい投稿で自動設定する場合
add_action('save_post', 'auto_post_thumbnail_image');
add_action('draft_to_publish', 'auto_post_thumbnail_image');
add_action('new_to_publish', 'auto_post_thumbnail_image');
add_action('pending_to_publish', 'auto_post_thumbnail_image');
add_action('future_to_publish', 'auto_post_thumbnail_image');
/////////////////////////////////////////////
// ここまで
/////////////////////////////////////////////

A8 の画像に対応させてみた

ドキュメントの中に <!–thum(n)–> と入れてもらうと何番目に現れるイメージを拾うか指定できます。
※ デフォルトは1番目
※ n は、何番目の img を拾うか指定しでます。
/////////////////////////////////////////////
//コピペ一発でWordpressの投稿時にアイキャッチを自動設定するカスタマイズ方法(YouTube対応版)
//http://nelog.jp/auto-post-thumbnail-custum
//楽天イメージタグ対応
//A8イメージタグ対応
//使用画像順番号指定対応 <!--thum(n)--> nは、アイキャッチに使用する画像準番号(<img の出現番号
// ※ youtube動画が入っている場合、これを指定できない。
//http://tecinfo.yuzumaru.co.jp/wp/
/////////////////////////////////////////////

//WP_Filesystemの利用
require_once(ABSPATH . '/wp-admin/includes/image.php');
//イメージファイルがサーバー内にない場合は取得する
function fetch_thumbnail_image($matches, $key, $post_content, $post_id,$youtube_sw){
	//デバッグ用パーツ
	//$wfp=fopen( WP_CONTENT_DIR.'/snap.txt','a');
	//fwrite($wfp, "loopmax=$loopmax\n"); 
	//fwrite($wfp, "POS1=$wpos\n"); 
	//fwrite($wfp, "POS2=$wpos2\n"); 
	//fclose($wfp);
	
	$wpos=0;
	$work="";
	if( $youtube_sw == 1){
		//正しいタイトルをイメージに割り当てる。IMGタグから抽出
		$imageTitle = '';
		preg_match_all('/<\s*img [^\>]*title\s*=\s*[\""\']?([^\""\'>]*)/i', $post_content, $matchesTitle);
		
		if (count($matchesTitle) && isset($matchesTitle[1])) {
			$imageTitle = $matchesTitle[1][$key];
		}
		//処理のためのURL取得
		$imageUrl = $matches[1][$key];
	}else{
		$wpos=mb_strpos($post_content,'<img');
		if($wpos>0){
			if(mb_strpos($post_content,"!--thum(")>=0 ){
				$loopmax=0;
				if( mb_strpos($post_content,"thum(")>=0 ){
					preg_match_all('/thum\((.*)\)/i'  , $post_content, $thum);
					$loopmax=$thum[1][0];
					$loopmax--;
				}
				while( $loopmax>0 ){
					$wpos2=mb_strpos($post_content,'<img',$wpos+1);
					if($wpos2>0){
						$wpos=$wpos2;
					}else{
						break;
					}
					$loopmax--;
				}
			} 
		}
	}
	if($wpos>0){
		$work=mb_substr($post_content,$wpos);
		$wpos=mb_strpos($work,'>');
		if($wpos>0){
			$work=mb_substr($work,0,$wpos+1);
			preg_match_all('/src\s*=\s*[\"\'](.*)[\"\']/i'  , $work, $matchesImage);
			preg_match_all('/title\s*=\s*[\"\'](.*)[\"\']/i', $work, $matchesTitle);
			if(mb_strpos($work,"a8.net")>=0 && mb_strpos($work,"bgt")>=0 ){
				$imageTitle = $matchesTitle[1][0];
				$imageUrl = $matchesImage[1][0];
			}else{
				$work="";
			}
		}
	}						

	//楽天イメージタグの処理
	$p=strpos($imageUrl,'?pc');
	if($p>0){
		$imgWork=mb_substr($imageUrl,$p);
		$imgWork=urldecode($imgWork);
		$p=strpos($imgWork,'=');
		if($p>0){
			$imgWork=mb_substr($imgWork,$p+1);
			$p=strpos($imgWork,'?');
			if($p>0){
				$imageUrl=mb_substr($imgWork,0,$p);
			}
		}
	}
	//ファイル名の取得
	$filename = substr($imageUrl, (strrpos($imageUrl, '/'))+1);
	if (!(($uploads = wp_upload_dir(current_time('mysql')) ) && false === $uploads['error'])){
		return null;
	}
	//ユニック(一意)ファイル名を生成
	$filename = wp_unique_filename( $uploads['path'], $filename );
	//ファイルをアップロードディレクトリに移動
	$new_file = $uploads['path'] . "/$filename";
	if(mb_strpos($work,"a8.net")>=0 && mb_strpos($work,"bgt")>=0 && $work!=''){
		$new_file=$new_file.".jpg";
	}
	
	if (!ini_get('allow_url_fopen')) {
		$file_data = curl_get_file_contents($imageUrl);
	} else {
		$file_data = @file_get_contents($imageUrl);
	}
	if (!$file_data) {
		return null;
	}
	
	file_put_contents($new_file, $file_data);
	
	//ファイルのパーミッションを正しく設定
	$stat = stat( dirname( $new_file ));
	$perms = $stat['mode'] & 0000666;
	@ chmod( $new_file, $perms );
	
	//ファイルタイプの取得。サムネイルにそれを利用
	if(mb_strpos($work,"a8.net")>=0 && mb_strpos($work,"bgt")>=0 && $work!=''){
		$wp_filetype = wp_check_filetype( $new_file, $mimes );
	}else{
		$wp_filetype = wp_check_filetype( $filename, $mimes );
	}
	extract( $wp_filetype );
	
	//ファイルタイプがない場合、これ以上進めない
	if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) ) {
		return null;
	}
	
	//URLを作成
	$url = $uploads['url'] . "/$filename";
	
	//添付(attachment)配列を構成
	$attachment = array(
		'post_mime_type' => $type,
		'guid' => $url,
		'post_parent' => null,
		'post_title' => $imageTitle,
		'post_content' => '',
	);
	
	$thumb_id = wp_insert_attachment($attachment, $file, $post_id);
	if ( !is_wp_error($thumb_id) ) {
    	//attachmentのアップデート
		wp_update_attachment_metadata( $thumb_id, wp_generate_attachment_metadata( $thumb_id, $new_file ) );
		update_attached_file( $thumb_id, $new_file );
	
    	return $thumb_id;
	}
	
	return null;
}

//投稿内の最初の画像をアイキャッチに設定する(Auto Post Thumnailプラグイン的な機能)
function auto_post_thumbnail_image() {
	global $wpdb;
	global $post;
	$post_id = $post->ID;
	
	//アイキャッチが既に設定されているかチェック
	if (get_post_meta($post_id, '_thumbnail_id', true) || get_post_meta($post_id, 'skip_post_thumb', true)) {
		return;
	}
	
	$post = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE id = $post_id");
	
	//正規表現にマッチしたイメージのリストを格納する変数の初期化
	$matches = array();
	
	//投稿本文からすべての画像を取得
	$youtube_sw=0;
	preg_match_all('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*)/i', $post[0]->post_content, $matches);
	//YouTubeのサムネイルを取得(画像がなかった場合)
	if (empty($matches[0])) {
		preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $post[0]->post_content, $match);
		if (!empty($match[1])) {
			$matches=array(); $matches[0]=$matches[1]=array('http://img.youtube.com/vi/'.$match[1].'/mqdefault.jpg');
			$youtube_sw=1;
		}
	}
	
	if (count($matches)) {
		foreach ($matches[0] as $key => $image) {
			//画像がイメージギャラリーにあったなら、サムネイルIDをCSSクラスに追加(イメージタグからIDを探す)
			preg_match('/wp-image-([\d]*)/i', $image, $thumb_id);
			$thumb_id = $thumb_id[1];
			
			//サムネイルが見つからなかったら、データベースから探す
			if (!$thumb_id) {
				$image = substr($image, strpos($image, '"')+1);
				$result = $wpdb->get_results("SELECT ID FROM {$wpdb->posts} WHERE guid = '".$image."'");
				$thumb_id = $result[0]->ID;
			}
			
			//それでもサムネイルIDが見つからなかったら、画像をURLから取得する
			if (!$thumb_id) {
				$thumb_id = fetch_thumbnail_image($matches, $key, $post[0]->post_content, $post_id, $youtube_sw);
			}
			
			//サムネイルの取得に成功したらPost Metaをアップデート
			if ($thumb_id) {
				update_post_meta( $post_id, '_thumbnail_id', $thumb_id );
				break;
			}
		}
	}
}
//新しい投稿で自動設定する場合
add_action('save_post', 'auto_post_thumbnail_image');
add_action('draft_to_publish', 'auto_post_thumbnail_image');
add_action('new_to_publish', 'auto_post_thumbnail_image');
add_action('pending_to_publish', 'auto_post_thumbnail_image');
add_action('future_to_publish', 'auto_post_thumbnail_image');
/////////////////////////////////////////////
// ここまで
/////////////////////////////////////////////

スポンサーリンク

スポンサーリンク

カテゴリー