Written by Anonymous
function auto_post_thumbnail_image($post_id) {
global $wpdb;
global $post;
if (!$post_id && isset($post->id)) {
$post_id = $post->id;
}
if (is_object($post_id) && isset($post_id->ID)) {
$post_id = $post_id->ID;
}
if (!$post) {
return;
}
//アイキャッチが既に設定されているかチェック
if (get_post_meta($post_id, '_thumbnail_id', true) || get_post_meta($post_id, 'skip_post_thumb', true)) {
return;
}
if (has_post_thumbnail()) {
return;
}
$the_post = $wpdb->get_results($wpdb->prepare("SELECT * FROM `{$wpdb->posts}` WHERE id = %d", $post_id));
// --- 修正箇所:コンテンツの展開 ---
$content = $the_post[0]->post_content;
$content = do_blocks($content);
$content = do_shortcode($content);
// -------------------------------
//正規表現にマッチしたイメージのリストを格納する変数の初期化
$matches = array();
//投稿本文からすべての画像を取得
preg_match_all('/<\s*img [^\>]*src\s*=\s*[\""\']?([^\""\'>]*).+?\/?>/i', $content, $matches);
//YouTubeのサムネイルを取得(画像がなかった場合)
if (empty($matches[0])) {
preg_match('%(?:youtube\.com/(?:user/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $content, $match);
if (!empty($match[1])) {
$matches = array();
$matches[0] = $matches[1] = array('https://i.ytimg.com/vi/'.$match[1].'/maxresdefault.jpg');
}
}
if (count($matches)) {
foreach ($matches[0] as $key => $image) {
$thumb_id = null;
//画像がイメージギャラリーにあったなら、サムネイルIDをCSSクラスに追加(イメージタグからIDを探す)
preg_match('/wp-image-([\d]*)/i', $image, $thumb_id);
if ( isset($thumb_id[1]) )
$thumb_id = $thumb_id[1];
//サムネイルが見つからなかったら、データベースから探す
if (!$thumb_id &&
//画像のパスにホームアドレスが含まれているとき
( strpos($image, home_url()) !== false ) ) {
preg_match('/src *= *"([^"]+)/i', $image, $m);
if ( isset($m[1]) ) {
$image_url = $m[1]; // 元コードの $image を上書きしないよう変数化
//wp_postsテーブルからguidがファイルパスのものを検索してIDを取得
$result = $wpdb->get_results($wpdb->prepare("SELECT ID FROM `{$wpdb->posts}` WHERE guid = %s", $image_url));
//IDをサムネイルをIDにセットする
if ( isset($result[0]) )
$thumb_id = $result[0]->ID;
}
//サムネイルなどで存在しないときはフルサイズのものをセットする
if ( !$thumb_id && isset($image_url) ) {
//ファイルパスの分割
$path_parts = pathinfo($image_url);
//サムネイルの追加文字列(-680x400など)を取得
preg_match('/-\d+x\d+$/i', $path_parts["filename"], $m);
//画像のアドレスにサイト名が入っていてサムネイル文字列が入っているとき
if ( isset($m[0]) ) {
//サムネイルの追加文字列(-680x400など)をファイル名から削除
$new_filename = str_replace($m[0], '', $path_parts["filename"]);
//新しいファイル名を利用してファイルパスを結語
$new_filepath = $path_parts["dirname"].'/'.$new_filename.'.'.$path_parts["extension"];
//wp_postsテーブルからguidがファイルパスのものを検索してIDを取得
$result = $wpdb->get_results($wpdb->prepare("SELECT ID FROM `{$wpdb->posts}` WHERE guid = %s", $new_filepath));
//IDをサムネイルをIDにセットする
if ( isset($result[0]) )
$thumb_id = $result[0]->ID;
}
}
}
//それでもサムネイルIDが見つからなかったら、画像をURLから取得する
if (!$thumb_id) {
// _v($matches);
$thumb_id = fetch_thumbnail_image($matches, $key, $content, $post_id);
}
//サムネイルの取得に成功したらPost Metaをアップデート
if ($thumb_id) {
update_post_meta( $post_id, '_thumbnail_id', $thumb_id );
break;
}
}
}
}