WordPress カスタマイズ カスタマイズ セキュリティ 伝えたいこと 備忘録

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

プラグイン使わずにアイキャッチ画像を自動生成・設定する方法

目次に行く・戻る

メルカリ招待コード:

所要時間目安: 17

This session is using  IPv4  is established in

今日は2025年10月30日です。

アイキャッチ画像とは何かということはわかると思いますので特に説明しませんが、ブログなどの記事に対するアイキャッチ画像を設定し忘れてしまったり、アイキャッチ画像を作ったり、アイキャッチ画像を設定し忘れてしまったりなど多いのではないでしょうか?そこでアイキャッチ画像をあらかじめ設定しておき、アイキャッチ画像を忘れてしまった時には自動的にアイキャッチ画像を設定することはコードのみで可能です。

それだけではなくタイトルから自動的にアイキャッチ画像を作成・生成し自動的にそのアイキャッチ画像を設定する方法です。プラグインなしでの方法です。

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

以下に最終的なアイキャッチ画像を自生生成作成して自動的にアイキャッチ画像を設定するコードを記載しておきます。参考にしていただけましたら幸いです。

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

function auto_generate_featured_image($post_id) { // 自動保存の場合は何もしない if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; }

// 投稿タイプが 'post' の場合のみ実行 if (get_post_type($post_id) !== 'post') { return; }

// 既にアイキャッチ画像が設定されている場合は何もしない if (has_post_thumbnail($post_id)) { return; }

// 投稿データを取得 $post = get_post($post_id); $title = $post->post_title;

// 画像のサイズ設定 $width = 800; $height = 400;

// 背景色とテキスト色の設定 $bg_color = [100, 150, 200]; // RGB $text_color = [255, 255, 255]; // RGB

// 画像を作成 $image = imagecreatetruecolor($width, $height);

// 背景色を設定 $background = imagecolorallocate($image, $bg_color[0], $bg_color[1], $bg_color[2]); imagefilledrectangle($image, 0, 0, $width, $height, $background);

// テキスト色を設定 $color = imagecolorallocate($image, $text_color[0], $text_color[1], $text_color[2]);

// フォントのパス(サーバーに存在するTTFフォントを指定してください) $font_path = __DIR__ . '/arial.ttf'; // 例: Arialフォント

// テキストのサイズと位置 $font_size = 20; $textbox = imagettfbbox($font_size, 0, $font_path, $title); $text_width = $textbox[2] - $textbox[0]; $text_height = $textbox[7] - $textbox[1]; $x = ($width - $text_width) / 2; $y = ($height - $text_height) / 2;

// テキストを描画 imagettftext($image, $font_size, 0, $x, $y, $color, $font_path, $title);

// 画像を一時ファイルとして保存 $upload_dir = wp_upload_dir(); $image_path = $upload_dir['path'] . '/auto-featured-' . $post_id . '.png'; imagepng($image, $image_path); imagedestroy($image);

// メディアライブラリに画像を追加 $attachment = [ 'post_mime_type' => 'image/png', 'post_title' => sanitize_file_name($title), 'post_content' => '', 'post_status' => 'inherit', ];

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

// アイキャッチ画像として設定 set_post_thumbnail($post_id, $attach_id); }

// 投稿が保存される際に関数を実行 add_action('save_post', 'auto_generate_featured_image');

以上をfunction.php内に追加し子テーマのfunction.phpにアップロードします。これだけでタイトルから自動的にアイキャッチ画像を作成し自動的にアイキャッチ画像を設定することができます。

※注意として、function.phpは大切なファイルですので必ずバックアップを取ってから行ってください。

以下、簡単な使い方(説明)です。

使用方法:

  1. 上記のコードをテーマの functions.php ファイルに追加します。
  2. コード内の $font_path をサーバー上に存在するTrueTypeフォント(.ttf)のパスに変更します。例としてArialフォントを使用していますが、他のフォントでも構いません。
  3. 投稿を新規作成または更新すると、自動的にアイキャッチ画像が生成され、設定されます。

注意点:

  • GDライブラリがPHPにインストールされている必要があります。インストールされていない場合は、サーバー管理者に依頼してください。
  • フォントファイル(例: arial.ttf)をテーマディレクトリに配置するか、適切なパスを指定してください。
  • 画像のデザインやテキストの描画方法は必要に応じてカスタマイズしてください。

他にもコードを編集してアイキャッチ画像を自動的に作成・生成して自動的にアイキャッチ画像を設定することは可能です。特にプラグインなどは使わずにできるので余計なプラグインはできるだけ導入(使いたくない)したくない方は上記コードにてアイキャッチ画像を自動的に生成・作成し、アイキャッチ画像を設定可能なので参考にしていただけましたら幸いです。

その他のアイキャッチ画像を自動生成・作成して自動的にアイキャッチ画像を設定する方法コードとしては、以下のようなコードでもできます。

ランダムに背景色や文字色が変わる仕様になっています。

/**
 * Automatically generate featured images for posts in WordPress.
 */

// Hook into the 'save_post' action add_action('save_post', 'auto_generate_featured_image', 10, 3);

/** * Generate a featured image automatically. * * @param int $post_id Post ID. * @param WP_Post $post Post object. * @param bool $update Whether this is an existing post being updated. */ function auto_generate_featured_image($post_id, $post, $update) { // Check if the post already has a featured image if (has_post_thumbnail($post_id)) { return; }

// Only generate for specific post types if ($post->post_type != 'post') { return; }

// Generate image parameters $width = 1200; $height = 630; $background_color = get_random_color(); $text_color = get_contrasting_color($background_color); $font_size = 40; $font_path = __DIR__ . '/fonts/arial.ttf'; // Ensure you have a TTF font in the specified path

// Create image $image = imagecreate($width, $height);

// Allocate colors $bg = imagecolorallocate($image, $background_color['red'], $background_color['green'], $background_color['blue']); $text_col = imagecolorallocate($image, $text_color['red'], $text_color['green'], $text_color['blue']);

// Add text (post title) $text = get_the_title($post_id); $bbox = imagettfbbox($font_size, 0, $font_path, $text); $text_width = $bbox[2] - $bbox[0]; $text_height = $bbox[7] - $bbox[1]; $x = ($width / 2) - ($text_width / 2); $y = ($height / 2) - ($text_height / 2); imagettftext($image, $font_size, 0, $x, $y, $text_col, $font_path, $text);

// Save the image to the uploads directory $upload_dir = wp_upload_dir(); $image_name = sanitize_title($text) . '-' . time() . '.png'; $image_path = $upload_dir['path'] . '/' . $image_name; imagepng($image, $image_path); imagedestroy($image);

// Attach the image to the post $attachment = array( 'post_mime_type' => 'image/png', 'post_title' => sanitize_file_name($image_name), 'post_content' => '', 'post_status' => 'inherit' );

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

// Set as featured image set_post_thumbnail($post_id, $attach_id); }

/** * Get a random color. * * @return array Associative array with 'red', 'green', 'blue' keys. */ function get_random_color() { return array( 'red' => rand(0, 255), 'green' => rand(0, 255), 'blue' => rand(0, 255), ); }

/** * Calculate a contrasting color for text. * * @param array $background Associative array with 'red', 'green', 'blue' keys. * @return array Associative array with 'red', 'green', 'blue' keys. */ function get_contrasting_color($background) { // Calculate brightness (Perceived luminance) $brightness = (($background['red'] * 299) + ($background['green'] * 587) + ($background['blue'] * 114)) / 1000; return $brightness > 125 ? array('red' => 0, 'green' => 0, 'blue' => 0) : array('red' => 255, 'green' => 255, 'blue' => 255); }

/** Automatically generate featured images for posts in WordPress. */

// Hook into the 'save_post' action add_action('save_post', 'auto_generate_featured_image', 10, 3);

/**

Generate a featured image automatically. *

@param int $post_id Post ID.

@param WP_Post $post Post object.

@param bool $update Whether this is an existing post being updated. */ function auto_generate_featured_image($post_id, $post, $update) { // Check if the post already has a featured image if (has_post_thumbnail($post_id)) { return; } // Only generate for specific post types if ($post->post_type != 'post') { return; } // Generate image parameters $width = 1200; $height = 630; $background_color = get_random_color(); $text_color = get_contrasting_color($background_color); $font_size = 40; $font_path = DIR . '/fonts/arial.ttf'; // Ensure you have a TTF font in the specified path // Create image $image = imagecreate($width, $height); // Allocate colors $bg = imagecolorallocate($image, $background_color['red'], $background_color['green'], $background_color['blue']); $text_col = imagecolorallocate($image, $text_color['red'], $text_color['green'], $text_color['blue']); // Add text (post title) $text = get_the_title($post_id); $bbox = imagettfbbox($font_size, 0, $font_path, $text); $text_width = $bbox[2] - $bbox[0]; $text_height = $bbox[7] - $bbox[1]; $x = ($width / 2) - ($text_width / 2); $y = ($height / 2) - ($text_height / 2); imagettftext($image, $font_size, 0, $x, $y, $text_col, $font_path, $text); // Save the image to the uploads directory $upload_dir = wp_upload_dir(); $image_name = sanitize_title($text) . '-' . time() . '.png'; $image_path = $upload_dir['path'] . '/' . $image_name; imagepng($image, $image_path); imagedestroy($image); // Attach the image to the post $attachment = array( 'post_mime_type' => 'image/png', 'post_title' => sanitize_file_name($image_name), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment($attachment, $image_path, $post_id); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata($attach_id, $image_path); wp_update_attachment_metadata($attach_id, $attach_data); // Set as featured image set_post_thumbnail($post_id, $attach_id); }

/**

Get a random color. *

@return array Associative array with 'red', 'green', 'blue' keys. */ function get_random_color() { return array( 'red' => rand(0, 255), 'green' => rand(0, 255), 'blue' => rand(0, 255), ); }

/**

Calculate a contrasting color for text. *

@param array $background Associative array with 'red', 'green', 'blue' keys.

@return array Associative array with 'red', 'green', 'blue' keys. */ function get_contrasting_color($background) { // Calculate brightness (Perceived luminance) $brightness = (($background['red'] * 299) + ($background['green'] * 587) + ($background['blue'] * 114)) / 1000; return $brightness > 125 ? array('red' => 0, 'green' => 0, 'blue' => 0) : array('red' => 255, 'green' => 255, 'blue' => 255); }

説明:

このコードは、WordPressの投稿が保存される際に自動的にアイキャッチ画像(Featured Image)を生成します。以下は主要な機能の概要です。

  1. 上記のコードをテーマの functions.php ファイルに追加します。
  2. コード内の $font_path をサーバー上に存在するTrueTypeフォント(.ttf)のパスに変更します。例としてArialフォントを使用していますが、他のフォントでも構いません。
  3. 注意点:

  4. フックの設定:
  • save_post アクションに auto_generate_featured_image 関数をフックしています。これにより、投稿が保存されるたびにこの関数が実行されます。
    • 既存のアイキャッチ画像をチェック:
    • 投稿に既にアイキャッチ画像が設定されている場合、処理を中断します。
      • 投稿タイプの確認:
      • この自動生成は 'post' タイプの投稿にのみ適用されます。他の投稿タイプには適用されません。
      • 画像の生成:
      • 指定された幅と高さで新しい画像を作成します。
      • 画像の保存と添付:
      • 生成された画像はWordPressのアップロードディレクトリに保存されます。
    • 画像は投稿に添付され、アイキャッチ画像として設定されます。

    注意点:

    • フォントファイル:
    • font_path で指定されたパスに有効なTTFフォントファイルが存在する必要があります。サーバー上にフォントファイルを配置し、正しいパスを設定してください。
    • GDライブラリ:
    • このコードはPHPのGDライブラリを使用しています。サーバーにGDライブラリがインストールされていることを確認してください。
    • エラーハンドリング:
    • 簡略化のため、エラーハンドリングは最低限となっています。実運用では、画像生成や保存時のエラー処理を追加することを推奨します。

    • セキュリティ:
    • 投稿タイトルが直接画像に描画されるため、適切なサニタイズ(sanitize_title など)を行っていますが、さらにセキュリティを強化する場合は追加の対策が必要です。

    この関数をテーマの functions.php ファイルやカスタムプラグインに追加することで、自動的にアイキャッチ画像が生成されるようになります。

    最後に、アイキャッチ画像を自動生成・作成して自動的にアイキャッチ画像を設定することができるアイキャッチ画像を自動生成コード作成ツールを以下に記載しておきます。

    <html>
    <head>
        <meta charset="UTF-8">
        <title>✨アイキャッチ画像自動生成ツール✨</title>
        <style>
            @keyframes bounce {
                0{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 20{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 50{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 80{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 100{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(0); }
                40{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(-30px); }
                60{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(-15px); }
            }
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
            .bounce {
                animation: bounce 2s infinite;
            }
            .fade-in {
                animation: fadeIn 1s forwards;
            }
        </style>
    </head>
    <body>
        <div style="text-align: center; padding: 20px;">
            <h1 style="font-size: 24px;">🎉 WordPress アイキャッチ自動生成ツール 🎨</h1>
            <div style="font-size: 100px;" id="emoji">🚀</div>
            <button id="generateBtn" style="padding: 10px 20px; font-size: 16px; cursor: pointer;">✨ 生成する ✨</button>
            <div id="codeContainer" style="margin-top: 20px; display: none; background-color: #f0f0f0; padding: 10px; border-radius: 10px; text-align: left;">
                <pre style="white-space: pre-wrap; word-wrap: break-word;">
    function generateFeaturedImage() {
        add_theme_support('post-thumbnails');
        
        function auto_generate_featured_image($post_id) {
            if (get_post_meta($post_id, '_thumbnail_id', true)) return;
    
    

    $post = get_post($post_id); $title = $post->post_title;

    $image = imagecreatetruecolor(800, 400); $bg_color = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, 800, 400, $bg_color);

    $text_color = imagecolorallocate($image, 0, 0, 0); imagestring($image, 5, 10, 180, $title, $text_color);

    $upload_dir = wp_upload_dir(); $image_path = $upload_dir['path'] . '/featured-' . $post_id . '.png'; imagepng($image, $image_path); imagedestroy($image);

    $attachment = array( 'post_mime_type' => 'image/png', 'post_title' => 'Featured Image for ' . $title, 'post_content' => '', 'post_status' => 'inherit' );

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

    add_action('save_post', 'auto_generate_featured_image'); } </pre> <button id="copyBtn" style="padding: 5px 10px; font-size: 14px; cursor: pointer;">📋 コピーする</button> </div> </div>

    <script> const generateBtn = document.getElementById('generateBtn'); const codeContainer = document.getElementById('codeContainer'); const emoji = document.getElementById('emoji'); const copyBtn = document.getElementById('copyBtn');

    generateBtn.addEventListener('click', () => { codeContainer.style.display = 'block'; codeContainer.classList.add('fade-in'); emoji.classList.add('bounce'); });

    copyBtn.addEventListener('click', () => { const code = codeContainer.querySelector('pre').innerText; navigator.clipboard.writeText(code).then(() => { copyBtn.innerText = '✅ コピー完了!'; setTimeout(() => { copyBtn.innerText = '📋 コピーする'; }, 2000); }); }); </script> </body> </html>

    上記コードを固定ページなどにてHTMLページとして作成すると以下のようなページが作成できます。ちょっとした遊び心ですね。

    以下、アイキャッチ画像自動生成ツールにて「生成する」を押下(押す)と以下のようなコード生成・作成されます。

    function generateFeaturedImage() {
        add_theme_support('post-thumbnails');
        
        function auto_generate_featured_image($post_id) {
            if (get_post_meta($post_id, '_thumbnail_id', true)) return;
    
    

    $post = get_post($post_id); $title = $post->post_title;

    $image = imagecreatetruecolor(800, 400); $bg_color = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, 800, 400, $bg_color);

    $text_color = imagecolorallocate($image, 0, 0, 0); imagestring($image, 5, 10, 180, $title, $text_color);

    $upload_dir = wp_upload_dir(); $image_path = $upload_dir['path'] . '/featured-' . $post_id . '.png'; imagepng($image, $image_path); imagedestroy($image);

    $attachment = array( 'post_mime_type' => 'image/png', 'post_title' => 'Featured Image for ' . $title, 'post_content' => '', 'post_status' => 'inherit' );

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

    add_action('save_post', 'auto_generate_featured_image'); }

    以下アイキャッチ画像を自動生成ツールを押下してみてください。

    ✨アイキャッチ画像自動生成ツール✨ @keyframes bounce { 0{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 20{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 50{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 80{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc}, 100{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(0); } 40{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(-30px); } 60{cef5aed0a4ddd38fb4a46370c0420b24042e11e5ea48583343b33cad007100cc} { transform: translateY(-15px); } } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .bounce { animation: bounce 2s infinite; } .fade-in { animation: fadeIn 1s forwards; }

    🎉 WordPress アイキャッチ自動生成ツール 🎨

    🚀
    function generateFeaturedImage() {
        add_theme_support('post-thumbnails');
        
        function auto_generate_featured_image($post_id) {
            if (get_post_meta($post_id, '_thumbnail_id', true)) return;
    
    

    $post = get_post($post_id); $title = $post->post_title;

    $image = imagecreatetruecolor(800, 400); $bg_color = imagecolorallocate($image, 255, 255, 255); imagefilledrectangle($image, 0, 0, 800, 400, $bg_color);

    $text_color = imagecolorallocate($image, 0, 0, 0); imagestring($image, 5, 10, 180, $title, $text_color);

    $upload_dir = wp_upload_dir(); $image_path = $upload_dir['path'] . '/featured-' . $post_id . '.png'; imagepng($image, $image_path); imagedestroy($image);

    $attachment = array( 'post_mime_type' => 'image/png', 'post_title' => 'Featured Image for ' . $title, 'post_content' => '', 'post_status' => 'inherit' );

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

    add_action('save_post', 'auto_generate_featured_image'); }
    const generateBtn = document.getElementById('generateBtn'); const codeContainer = document.getElementById('codeContainer'); const emoji = document.getElementById('emoji'); const copyBtn = document.getElementById('copyBtn');

    generateBtn.addEventListener('click', () => { codeContainer.style.display = 'block'; codeContainer.classList.add('fade-in'); emoji.classList.add('bounce'); });

    copyBtn.addEventListener('click', () => { const code = codeContainer.querySelector('pre').innerText; navigator.clipboard.writeText(code).then(() => { copyBtn.innerText = '✅ コピー完了!'; setTimeout(() => { copyBtn.innerText = '📋 コピーする'; }, 2000); }); });

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

あなたにおすすめ


Multiplex 広告

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

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

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


カウントダウンタイマー

おすすめの記事一部広告

Total357


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

目次に戻る

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

-WordPress, カスタマイズ, カスタマイズ, セキュリティ, 伝えたいこと, 備忘録

目次に戻る

目次に戻る


コメントを表示(0)

コメントを書く

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


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

新着コメント