GeneratePressの新着7日以内の記事カードにNEWマークをつけるカスタマイズ

海外のWordPressテーマGeneratePressを利用しています。

とても良いテーマですね。基本のWordPressの公式ディレクトリに掲載しているテーマを適用して、カスタマイズしました。

今回は、GeneratePressのトップの新着記事カードに7日以内に投稿した記事にNEWマークをつけるカスタマイズについてご紹介します。

1.以下のコードをCodeSnippetsに追記します。

/**
 * 公開から7日以内の記事カードに「NEW」を表示
 */
function hirochan_add_new_badge_after_entry_content() {

	// 投稿一覧・アーカイブ・検索結果だけで表示
	if ( ! is_home() && ! is_archive() && ! is_search() ) {
		return;
	}

	// 通常の投稿だけを対象にする
	if ( 'post' !== get_post_type() ) {
		return;
	}

	// 初回公開日時を取得
	$published_time = get_post_time( 'U', true );
	$current_time   = time();
	$seven_days     = 7 * DAY_IN_SECONDS;

	// 公開から7日以内なら表示
	if (
		$published_time &&
		$current_time >= $published_time &&
		( $current_time - $published_time ) < $seven_days
	) {
		echo '<span class="entry-new-badge" aria-label="公開から7日以内">NEW</span>';
	}
}
add_action(
	'generate_after_entry_content',
	'hirochan_add_new_badge_after_entry_content'
);

以上で、記事カードにNEWマークが表示されました。

2.CSSで外観を整えます。

/* NEWマーク配置の基準 */
.blog .inside-article,
.archive .inside-article,
.search .inside-article {
    position: relative;
}

/* NEWマーク */
.entry-new-badge {
    position: absolute;
    top: 14px;
    right: 14px;
    z-index: 2;

    display: inline-flex;
    align-items: center;
    justify-content: center;

    min-width: 3.5em;
    padding: 0.4em 0.75em;
    border-radius: 999px;

    color: #fff;
    background-color: #46705b;
    font-size: 11px;
    font-weight: 700;
    line-height: 1;
    letter-spacing: 0.08em;

    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.14);
    pointer-events: none;
}

/* スマートフォン */
@media (max-width: 768px) {
    .entry-new-badge {
        top: 10px;
        right: 10px;
        font-size: 10px;
    }
}

以上で、NEWマークの実装ができました。

GeneratePressはフックも豊富でカスタマイズ性がとても高いです。

また、GP PremiumやGeneratePressOneなど、機能がさらに豊富なプレミアムプランもありますので、ぜひ利用してみると素敵なサイトができるかと思います。

GeneratePress公式サイトはこちらです。

https://generatepress.com

sample↓