【SWELL】記事タイトルに「新着!」を付けるカスタマイズ

○○日以内の新着記事のみに「新着!」を付けるカスタマイズ方法をご紹介します。

表示する日数の変更やCSSでデザインの変更も可能です。

またWordPressテーマ「SWELL」に対応したCSSと変数を使用しているので、サイトに馴染むデザインになると思います。

目次

記事タイトルに「新着!」を付けるコード

上図は当記事で作成した新着ラベルのデザインになります。

// 投稿後○○日以内に「新着!」ラベルをタイトルに追加する
function add_new_label_to_post_title($title, $post_id) {
	// 管理画面やRSSでは除外
	if (is_admin() || is_feed()) {
		return $title;
	}

	// メインクエリで、投稿タイプが「post」のときのみ適用
	if (get_post_type($post_id) !== 'post') {
		return $title;
	}

	// // 表示ページを限定する場合
	// if (!is_home() && !is_archive() && !is_search()) {
	//		return $title;
	// }

	// 新着の定義(○○日以内)
	$days_limit = 3;

	$post_timestamp = get_post_time('U', true, $post_id); // 投稿日時をUNIXタイムスタンプで取得
	$current_time = current_time('timestamp');

	$days_since_post = ($current_time - $post_timestamp) / DAY_IN_SECONDS;

	if ($days_since_post <= $days_limit) {
		$label_html = '<span class="p-postList__newLabel">新着!</span> ';
		return $label_html . $title;
	}


	return $title;
}
add_filter('the_title', 'add_new_label_to_post_title', 1, 2);

上記のコードをSWELL子テーマの「functions.php」に張り付けてください。

$days_limitの数字を変更する事で、表示する期間を変える事ができます。

.p-postList__newLabel {
	display: inline-flex;
	justify-content: center;
	align-items: center;
	margin-right: .25em;
	padding: .125em .25em;
	border-radius: .25em;
	background: var(--color_deep01);
	color: var(--color_pale01);
	font-size: 0.75em;
}

上記のコードをSWELL子テーマの「style.css」に張り付けてください。

よかったらシェアしてね!
  • URLをコピーしました!
目次