はじめに
以下の内容を実現します。
投稿のある日付に、その投稿のアイキャッチ画像を表示します。
なお、該当日に複数の投稿がある場合は、その日に公開された最新の投稿のアイキャッチ画像を表示します。
この記事では、この方法について説明します。
実装手順
以下のコードをfunctions.phpに追加します。
// カレンダーを変更
add_filter('get_calendar', function ($calendar) {
// 日付リンクから年月日を取得
return preg_replace_callback(
'#<a (href="[^"]*/(\d{4})/(\d{1,2})/(\d{1,2})/")#',
function ($m) {
// 該当日の最新の公開済み投稿を取得
$ids = get_posts([
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'fields' => 'ids',
'orderby' => 'date',
'order' => 'DESC',
'date_query' => [[
'year' => (int) $m[2],
'month' => (int) $m[3],
'day' => (int) $m[4],
]],
]);
// アイキャッチ画像URLを取得
$url = get_the_post_thumbnail_url($ids[0], 'full');
// アイキャッチ画像がない場合は処理対象外
if (!$url) {
return $m[0];
}
// クラスと背景画像を設定
return '<a class="calender-img" style="background-image:url(' . esc_url($url) . ');" ' . $m[1];
},
// カレンダー全体を置換
$calendar
);
});
// フロント用JS・CSSを追加
add_action('wp_enqueue_scripts', function () {
ob_start();
?>
.body .wp-calendar-table {
td {
background-color: transparent;
height: 100px;
vertical-align: top;
a {
background-color: unset;
color: unset;
height: 100%;
&.calender-img {
background-position-x: center;
background-position-y: 1.8em;
background-repeat: no-repeat;
background-size: cover;
}
}
}
}
<?php
$handle ='calendar-thumbnail';
wp_register_style($handle, false);
wp_enqueue_style($handle);
wp_add_inline_style($handle, ob_get_clean());
});
さいごに
今回紹介した方法を使えば、WordPressのカレンダーに投稿のアイキャッチ画像を表示できるようになります。
これにより、カレンダーの日付をクリックすると、関連する投稿のアイキャッチが視覚的に表示され、サイト訪問者にとって直感的で魅力的なインターフェイスが提供されます。


