WordPress カスタマイズ 伝えたいこと 備忘録

プロモーションを含みます

プラグイン使わずにアイキャッチ画像自動生成コード

目次に行く・戻る

メルカリ招待コード:

所要時間目安: 8

This session is using  IPv4  is established in

今日は2025年11月3日です。

アイキャッチ画像を毎回設定するために、いろいろと作成したらりフリー素材を使用したり意外と大変ですね。そこで、プラグインを使用してのアイキャッチ画像自動生成をするコードを作成してみました。背景色やフォントなどを指定し自動保存時にはアイキャッチ画像を設定せずに投稿時にタイトルを中央部分に設定したものになります。

この記事を読む方へのオススメ

アイキャッチ画像自動生成コードはいかになります。

/**
 * 自動的にアイキャッチ画像を生成して設定する関数
 * 
 * この関数は投稿が保存される際に自動的にアイキャッチ画像を生成し、設定します。
 * 画像には投稿のタイトルがテキストとして描画されます。
 */
function generate_featured_image_with_title_url_category( $post_id ) {
    if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;
    if ( wp_is_post_revision($post_id) ) return;
    if ( get_post_type($post_id) !== 'post' ) return;
    if ( has_post_thumbnail($post_id) ) return;

$post = get_post($post_id); if ( !$post ) return;

$title = get_the_title($post_id); $site_url = get_bloginfo('url');

// カテゴリ名取得(複数ある場合は最初のみ使用) $categories = get_the_category($post_id); $category_name = $categories && ! is_wp_error($categories) ? $categories[0]->name : '';

// 設定 $width = 1200; $height = 630; $font_size = 20; $font_file = __DIR__ . '/fonts/ARIAL.TTF'; // フォントをテーマ内に配置

// 透過PNG用のTrueColor画像を作成 $image = imagecreatetruecolor($width, $height); // アルファチャネルを有効にし、完全なアルファチャネル情報を保存 imagealphablending($image, false); imagesavealpha($image, true);

// 背景色を青(rgba(0, 0, 250, 1))に設定 $bg_color = imagecolorallocatealpha($image, 0, 0, 250, 0); // 透過なし imagefill($image, 0, 0, $bg_color);

// 色設定 $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0);

// --- タイトル(中央) --- $bbox = imagettfbbox($font_size, 0, $font_file, $title); $text_width = $bbox[2] - $bbox[0]; $x = ($width - $text_width) / 2; $y = ($height / 2) + ($font_size / 2);

$offsets = [-1, 0, 1]; foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $font_size, 0, $x + $ox, $y + $oy, $black, $font_file, $title); } } imagettftext($image, $font_size, 0, $x, $y, $white, $font_file, $title);

// --- サイトURL(右下) --- $url_font_size = 14; $url_bbox = imagettfbbox($url_font_size, 0, $font_file, $site_url); $url_width = $url_bbox[2] - $url_bbox[0]; $url_x = $width - $url_width - 20; $url_y = $height - 20;

foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $url_font_size, 0, $url_x + $ox, $url_y + $oy, $black, $font_file, $site_url); } } imagettftext($image, $url_font_size, 0, $url_x, $url_y, $white, $font_file, $site_url);

// --- カテゴリ名(左下) --- if ( $category_name ) { $cat_font_size = 14; $cat_bbox = imagettfbbox($cat_font_size, 0, $font_file, $category_name); $cat_x = 20; $cat_y = $height - 20;

foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $cat_font_size, 0, $cat_x + $ox, $cat_y + $oy, $black, $font_file, $category_name); } } imagettftext($image, $cat_font_size, 0, $cat_x, $cat_y, $white, $font_file, $category_name); }

// 保存・添付処理 $upload_dir = wp_upload_dir(); $filename = 'generated-thumb-' . $post_id . '.png'; // 拡張子をPNGに変更 $filepath = $upload_dir['path'] . '/' . $filename;

// PNG形式で保存 imagepng($image, $filepath); imagedestroy($image);

$filetype = wp_check_filetype($filename, null); $attachment = [ 'post_mime_type' => $filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ];

$attach_id = wp_insert_attachment($attachment, $filepath, $post_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filepath); wp_update_attachment_metadata($attach_id, $attach_data);

set_post_thumbnail($post_id, $attach_id); } add_action('save_post', 'generate_featured_image_with_title_url_category');

上記のコードを子テーマのfunction.phpに追加すると背景色が薄い青色で、タイトルを中央部分にし縁取りされてサイトのURLが右下に表示されるようになり左下にカテゴリを表示されるようになります。

フォントは、ARIAL.TTF(arial.ttf)に指定している為、サーバー内にfontフォルダディレクトリを作りfontフォルダ内にARIAL.TTF(arial.ttf)をアップロードしてください。

他にも、sans-selifJP.ttfなど日本語が使用可能なフォントであれば文字化けしないので、フォントはご自分の好みに合わせて変更してみてください。

上記のように投稿前は自動的にアイキャッチ画像が設定されます。

背景色をグレー色や黒色などの場合は以下のようになります。

背景色がグレー色の場合です。

背景色を透過させないのであれば、jpg画像にて生成するfunction.phpのコードは以下になります。

/**
 * 自動的にアイキャッチ画像を生成して設定する関数
 * 
 * この関数は投稿が保存される際に自動的にアイキャッチ画像を生成し、設定します。
 * 画像には投稿のタイトルがテキストとして描画されます。
 */

function generate_featured_image_with_title_url_category( $post_id ) { if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return; if ( wp_is_post_revision($post_id) ) return; if ( get_post_type($post_id) !== 'post' ) return; if ( has_post_thumbnail($post_id) ) return;

$post = get_post($post_id); if ( !$post ) return;

$title = get_the_title($post_id); $site_url = get_bloginfo('url');

// カテゴリ名取得(複数ある場合は最初のみ使用) $categories = get_the_category($post_id); $category_name = $categories && ! is_wp_error($categories) ? $categories[0]->name : '';

// 設定 $width = 1200; $height = 630; $font_size = 20; $font_file = __DIR__ . '/fonts/ARIAL.TTF'; // フォントをテーマ内に配置

$image = imagecreatetruecolor($width, $height); $bg_color = imagecolorallocate($image, 200, 200, 200); // グレー imagefill($image, 0, 0, $bg_color);

// 色設定 $white = imagecolorallocate($image, 255, 255, 255); $black = imagecolorallocate($image, 0, 0, 0);

// --- タイトル(中央) --- $bbox = imagettfbbox($font_size, 0, $font_file, $title); $text_width = $bbox[2] - $bbox[0]; $x = ($width - $text_width) / 2; $y = ($height / 2) + ($font_size / 2);

$offsets = [-1, 0, 1]; foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $font_size, 0, $x + $ox, $y + $oy, $black, $font_file, $title); } } imagettftext($image, $font_size, 0, $x, $y, $white, $font_file, $title);

// --- サイトURL(右下) --- $url_font_size = 14; $url_bbox = imagettfbbox($url_font_size, 0, $font_file, $site_url); $url_width = $url_bbox[2] - $url_bbox[0]; $url_x = $width - $url_width - 20; $url_y = $height - 20;

foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $url_font_size, 0, $url_x + $ox, $url_y + $oy, $black, $font_file, $site_url); } } imagettftext($image, $url_font_size, 0, $url_x, $url_y, $white, $font_file, $site_url);

// --- カテゴリ名(左下) --- if ( $category_name ) { $cat_font_size = 14; $cat_bbox = imagettfbbox($cat_font_size, 0, $font_file, $category_name); $cat_x = 20; $cat_y = $height - 20;

foreach ($offsets as $ox) { foreach ($offsets as $oy) { if ($ox === 0 && $oy === 0) continue; imagettftext($image, $cat_font_size, 0, $cat_x + $ox, $cat_y + $oy, $black, $font_file, $category_name); } } imagettftext($image, $cat_font_size, 0, $cat_x, $cat_y, $white, $font_file, $category_name); }

// 保存・添付処理 $upload_dir = wp_upload_dir(); $filename = 'generated-thumb-' . $post_id . '.jpg'; $filepath = $upload_dir['path'] . '/' . $filename;

imagejpeg($image, $filepath, 90); imagedestroy($image);

$filetype = wp_check_filetype($filename, null); $attachment = [ 'post_mime_type' => $filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ];

$attach_id = wp_insert_attachment($attachment, $filepath, $post_id); require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata($attach_id, $filepath); wp_update_attachment_metadata($attach_id, $attach_data);

set_post_thumbnail($post_id, $attach_id); } add_action('save_post', 'generate_featured_image_with_title_url_category');

過去のアイキャッチ画像自動生成コードに関する記事は以下になります。参考にしてみてください。

以下の最新版のアイキャッチ画像自動生成コードも参考にしてみていください。

あなたにおすすめ


Multiplex 広告

入学入社まであと…入学入社祝いはどんなPresent(プレゼント)でどのように過ごされますか?

ホワイトデープレゼントは以下などの豊富なキャンペーン商品から選ぶと良いと思います。

ブログサービスが始まってから:


カウントダウンタイマー

おすすめの記事一部広告

Total560


アドセンス336pxPC閲覧記事下表示1つ目コード

目次に戻る

よろしかったらシェアよろしくお願いします。

-WordPress, カスタマイズ, 伝えたいこと, 備忘録

目次に戻る

目次に戻る


コメントを表示(0)

コメントを書く

メールアドレスが公開されることはありません。 が付いている欄は必須項目です


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

新着コメント