はじめに
以下の質問に回答します。
通常、アイキャッチ画像は元のサイズのまま表示されます。
そのため、縦長の画像を使用すると、表示エリアが縦に伸び、本文が画面外に押し出されてしまうことがあります。
そこで、あらかじめ設定した画像の比率に合わせて、アイキャッチ画像の表示サイズを統一します。
ただし、この調整によって縦長の画像では左右に余白が生じる場合があります。
この余白を埋めるため、元の画像をぼかして背景に使用し、アイキャッチ画像の背後に重ねて表示します。
なお、これはCSSによる視覚的な演出にすぎないため、サムネイル画像には反映されません。
この記事では、この方法について説明します。
さらに、背景のぼかしを画像として合成し、その画像をアイキャッチとして直接設定する方法についても説明します。
アイキャッチ画像の背後に重ねて表示する方法
完成イメージ

実装手順
以下の手順で実装します。
- ラベルPHPを追加
以下のコードをfunctions.phpに追加します。
// メタボックスを追加 add_action('add_meta_boxes', function () { add_meta_box( 'vertical_featured_blur', '縦アイキャッチ背景ぼかし設定', 'vertical_featured_blur', 'post', 'side', 'default' ); }); /** * メタボックスの入力フォームを出力 * * @param WP_Post $post 現在の投稿オブジェクト * @return void */ if (!function_exists('vertical_featured_blur')): function vertical_featured_blur($post) { $value = get_post_meta($post->ID, 'my_image_check', true); wp_nonce_field('vertical_featured_blur_action', 'vertical_featured_blur_nonce'); ?> <label for="vertical_featured_blur"> <input type="checkbox" name="vertical_featured_blur" id="vertical_featured_blur" value="1" <?php checked($value, '1'); ?>> 縦アイキャッチ背景ぼかし </label> <?php } endif; // 投稿データを保存 add_action('save_post', function ($post_id) { // nonceチェック if (!isset($_POST['vertical_featured_blur_nonce']) || !wp_verify_nonce($_POST['vertical_featured_blur_nonce'], 'vertical_featured_blur_action')) { return; } // 自動保存チェック if ((defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) || wp_is_post_autosave($post_id)) { return; } // リビジョンは除外 if (wp_is_post_revision($post_id)) { return; } // 権限チェック if (!current_user_can('edit_post', $post_id)) { return; } $value = (isset($_POST['vertical_featured_blur']) && $_POST['vertical_featured_blur'] === '1') ? 1 : 0; update_post_meta($post_id, 'my_image_check', $value); }); // フロント用JS・CSSを追加 add_action('wp_enqueue_scripts', function () { if (!is_singular('post')) { return; } $post_id = get_the_ID(); $blur_on = get_post_meta($post_id, 'my_image_check', true); if (!$blur_on || !has_post_thumbnail($post_id)) { return; } $thumbnail_url = get_the_post_thumbnail_url($post_id, 'full'); if (!$thumbnail_url) { return; } $url = esc_url($thumbnail_url); ob_start(); ?> .eye-catch::before { background-image: url("<?php echo $url; ?>"); content: ""; } <?php $handle = 'vertical-featured'; wp_register_style($handle, false); wp_enqueue_style($handle); wp_add_inline_style($handle, ob_get_clean()); }); - ラベルCSSを追加
以下のコードをstyle.cssに追加します。
.eye-catch { aspect-ratio: var(--card-ratio); height: auto; overflow: hidden; img { display: block; height: 100%; margin: 0 auto; object-fit: contain; position: relative; } &::before { --blur: 5px; background-position: center; background-size: cover; bottom: calc(-1 * var(--blur)); filter: blur(var(--blur)); left: calc(-1 * var(--blur)); position: absolute; right: calc(-1 * var(--blur)); top: calc(-1 * var(--blur)); } }



