2025年3月9日 (日曜日)↓における週間月間人気記事トップ3は?↓
- 本日
- 週間
- 月間
-
ステアリング交換とステアリングスイッチの増設と外し方後期型仕様に 5PV
NISSANエクストレイルは日産の中でも人気のSUV車です。そのエクストレイルは今年の6月8日にT32型の後期型がマイナーチェンジして発売されました。新しい後期型にはメーカーオプションで話題の半分自動…
-
先日も書きましたWindows10の不具合?に関することです。 不具合と言うのか仕様と言えば良いのかわかりませんが、とにかくWindows10にアップグレードしたりWindows10に若干古めのアプリ…
-
ナビテレビが見れなくなった時ICカードが正常に動作しませんでした対処方法 4PV
本日ではなく昨日になってしまいますが、それまでカーナビで地デジ対応のナビで突然エンジンをかけなおしたら・・・・・・。 「ICカードが正常に動作しませんでした。販売店にお問い合わせください。」 なんてい…
-
カーメイトのエンジンスターターでエラー15表示と対処方法 28PV
夏冬に特に重宝するのが、エンジンスターターです。 メーカーはCARMATEやCOMTECユピテルなど各社ありますが、一番のオススメはリモコンから多くの情報を得ることができるカーメイト製品です。 なぜか…
-
ナビテレビが見れなくなった時ICカードが正常に動作しませんでした対処方法 23PV
本日ではなく昨日になってしまいますが、それまでカーナビで地デジ対応のナビで突然エンジンをかけなおしたら・・・・・・。 「ICカードが正常に動作しませんでした。販売店にお問い合わせください。」 なんてい…
-
エクストレイルT32運転席側バイザーメッキモール剥がれ修復方法とオススメ両面テープ 22PV
車の購入後、乗ろうが乗らまいが経年劣化というものは付きものなのですが、特にプラスチック部分や両面テープ部分などは経年劣化がどうしても起きてきてしまいます。 そんな車でも長めにお気に入りの愛車となれば長…
-
カーメイトのエンジンスターターでエラー15表示と対処方法 28PV
夏冬に特に重宝するのが、エンジンスターターです。 メーカーはCARMATEやCOMTECユピテルなど各社ありますが、一番のオススメはリモコンから多くの情報を得ることができるカーメイト製品です。 なぜか…
-
ナビテレビが見れなくなった時ICカードが正常に動作しませんでした対処方法 23PV
本日ではなく昨日になってしまいますが、それまでカーナビで地デジ対応のナビで突然エンジンをかけなおしたら・・・・・・。 「ICカードが正常に動作しませんでした。販売店にお問い合わせください。」 なんてい…
-
エクストレイルT32運転席側バイザーメッキモール剥がれ修復方法とオススメ両面テープ 22PV
車の購入後、乗ろうが乗らまいが経年劣化というものは付きものなのですが、特にプラスチック部分や両面テープ部分などは経年劣化がどうしても起きてきてしまいます。 そんな車でも長めにお気に入りの愛車となれば長…
今日は2025年3月9日です。
2025年3月9日 (日曜日)本日の人気記事トップ10
アイキャッチ画像とは何かということはわかると思いますので特に説明しませんが、ブログなどの記事に対するアイキャッチ画像を設定し忘れてしまったり、アイキャッチ画像を作ったり、アイキャッチ画像を設定し忘れてしまったりなど多いのではないでしょうか?そこでアイキャッチ画像をあらかじめ設定しておき、アイキャッチ画像を忘れてしまった時には自動的にアイキャッチ画像を設定することはコードのみで可能です。
それだけではなくタイトルから自動的にアイキャッチ画像を作成・生成し自動的にそのアイキャッチ画像を設定する方法です。プラグインなしでの方法です。
以下に最終的なアイキャッチ画像を自生生成作成して自動的にアイキャッチ画像を設定するコードを記載しておきます。参考にしていただけましたら幸いです。
/**
* 自動的にアイキャッチ画像を生成して設定する関数
*
* この関数は投稿が保存される際に自動的にアイキャッチ画像を生成し、設定します。
* 画像には投稿のタイトルがテキストとして描画されます。
*/
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は大切なファイルですので必ずバックアップを取ってから行ってください。
以下、簡単な使い方(説明)です。
使用方法:
- 上記のコードをテーマの
functions.php
ファイルに追加します。 - コード内の
$font_path
をサーバー上に存在するTrueTypeフォント(.ttf)のパスに変更します。例としてArialフォントを使用していますが、他のフォントでも構いません。 - 投稿を新規作成または更新すると、自動的にアイキャッチ画像が生成され、設定されます。
注意点:
- 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)を生成します。以下は主要な機能の概要です。
- 上記のコードをテーマの
functions.php
ファイルに追加します。 - コード内の
$font_path
をサーバー上に存在するTrueTypeフォント(.ttf)のパスに変更します。例としてArialフォントを使用していますが、他のフォントでも構いません。 - フックの設定:
注意点:
- save_post アクションに auto_generate_featured_image 関数をフックしています。これにより、投稿が保存されるたびにこの関数が実行されます。
- 既存のアイキャッチ画像をチェック:
- 投稿に既にアイキャッチ画像が設定されている場合、処理を中断します。
- 投稿タイプの確認:
- この自動生成は 'post' タイプの投稿にのみ適用されます。他の投稿タイプには適用されません。
- 画像の生成:
- 指定された幅と高さで新しい画像を作成します。
- 画像の保存と添付:
- 生成された画像はWordPressのアップロードディレクトリに保存されます。
- 画像は投稿に添付され、アイキャッチ画像として設定されます。
- フォントファイル:
- font_path で指定されたパスに有効なTTFフォントファイルが存在する必要があります。サーバー上にフォントファイルを配置し、正しいパスを設定してください。
- GDライブラリ:
- このコードはPHPのGDライブラリを使用しています。サーバーにGDライブラリがインストールされていることを確認してください。
- エラーハンドリング:
簡略化のため、エラーハンドリングは最低限となっています。実運用では、画像生成や保存時のエラー処理を追加することを推奨します。
- セキュリティ:
- 投稿タイトルが直接画像に描画されるため、適切なサニタイズ(sanitize_title など)を行っていますが、さらにセキュリティを強化する場合は追加の対策が必要です。
-
放射性物質半減期問題は?ベクレル(Bq)とシーベルト(Sv)違い
東日本大震災の、 月命日である11日に改めて、 放射能に関して記載しておきたいと思います。 なお、この記事は私が別のブログサービスで以前に投稿したものです。(2011年3月26…
-
PC Windows10 カスタマイズ 不具合 伝えたいこと 備忘録 設定
ブログランキングなんて関係ない書く楽しみと喜び悦びと嬉しさはお礼のコメント頂いた時…。
ブログはある意味趣味でもあり、続けている人にとっては日常のひとコマだと思われます。 苦痛やきついといった思いが(強すぎると)あると、なかなか続けられないものだと思います。本当に日課に自然となっているよ…
-
PC Windows10 不具合 伝えたいこと 備忘録 設定
Windows10スタートボタン効かない,タスクバークリック出来ない対処方法
今日パソコンを立ち上げた所デスクトップの下部に表示されているタスクバー部分の、 クイック起動メニューはクリックできました。 しかし…。 パソコンをシャットダウンしようとスタートボタン・スタートメニュー…
-
アイキャッチ画像を設定してみた。
よく言うアイキャッチ!!正直めんどくさいですよね。でも、訪問者やTwitter、Facebookなどにサムネイル表示される際に、自分のブログの記事にアイキャッチ(画像?)があると…。
-
小林麻央さんの病状も気になるが北斗晶さんの病状も気になる…。
私の従兄弟のお嫁さんが数年前に片方の乳房、そして今年両方の乳房を全摘手術…。再従兄弟も2年前に乳がんが発覚し片方の乳房を全摘手術したこともあり・・・・・・。先日、夫の市川海老蔵さんが会見を開いて、 妻…
- カーメイトのエンジンスターターでエラー15表示と対処方法117
- エクストレイルT32運転席側バイザーメッキモール剥がれ修復方法とオススメ両面テープ89
- ナビテレビが見れなくなった時ICカードが正常に動作しませんでした対処方法84
- アイドリングストップシステム異常警告灯表示対処方法54
- 車のキーナンバー確認方法。キーレス紛失や壊れた時48
- キッチンシンク下がドブ臭い下水臭い原因と解決方法33
- エクストレイルフォグランプが下を向きすぎている光軸調整方法32
- エクストレイルT32マイナーチェンジ後ステアリング外し方31
- ECUをリセットする方法。アイドリング不安定だったのでしょうがなく29
- Windows11 24H2不具合エクスプローラーのツールバー詳細 (…)が下に表示でなく上に表示解決方法27
注意点:
この関数をテーマの functions.php
ファイルやカスタムプラグインに追加することで、自動的にアイキャッチ画像が生成されるようになります。
最後に、アイキャッチ画像を自動生成・作成して自動的にアイキャッチ画像を設定することができるアイキャッチ画像を自動生成コード作成ツールを以下に記載しておきます。
<html>
<head>
<meta charset="UTF-8">
<title>✨アイキャッチ画像自動生成ツール✨</title>
<style>
@keyframes bounce {
0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
40% { transform: translateY(-30px); }
60% { 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');
}
以下アイキャッチ画像を自動生成ツールを押下してみてください。
🎉 WordPress アイキャッチ自動生成ツール 🎨
お買い物対象期間2025年2月28日(金) 9:00 ~ 2025年3月4日(火) 23:59
まで、セールイベントスマイルSALE-新生活を開催.jpg)
「伝えたいこと, 備忘録, WordPress, カスタマイズ, カスタマイズ, セキュリティ」の人気記事

ホワイトデーまであと…ホワイトデーはどんなPresent(プレゼント)でどのように過ごされますか?
ホワイトデープレゼントは以下などの豊富なキャンペーン商品から選ぶと良いと思います。
おすすめ!!
世界中でNo.1のシャアを誇るAmazonでのお得なお買い物でお得をしよう!!ネット通販なので、もちろん24時間年中無休です。健康商品から食品、車カスタマイズ商品、大手家電メーカー商品やパソコンの自作サプライ商品、その他アマゾン・プライムでは映画やドラマなど多くの作品や番組を見ることができます。マスクなど衛生商品も今では必須アイテム。一番信用できて一番商品数の多いAmazonでの買い物が絶対にオススメ!!
あなたにおすすめな関連記事
おすすめの記事一部広告
よろしかったらシェアよろしくお願いします。
comment