Blog

【WordPress】月別アーカイブの表示形式を変更する方法

2021.08.26 WordPress

WordPressの月別アーカイブは、デフォルトの状態だと「2021年7月」というような表示形式です。

今回は、この月別アーカイブの表示形式を「2021.7」「2021.07」「July 2021」という形に変更する方法をまとめたいと思います。

get_archives_link関数をテーマに直に書く場合でも、ウィジェットを利用する場合でも両方に適用されます。

月別アーカイブの表示形式を「2021.7」に変更

/* 月別アーカイブの表示形式を「2021.7」に変更
---------------------------------------------------------- */
function bw_get_archives_link($str){
	$str = str_replace('年','.',$str);
	$str = str_replace('月','',$str);
	return $str;
}
add_filter('get_archives_link', 'bw_get_archives_link');

str_replaceで「年」を「.」に、「月」を空文字に置き換えています。

月別アーカイブの表示形式を「2021.07」に変更

/* 月別アーカイブの表示形式を「2021.07」に変更
---------------------------------------------------------- */
add_filter('gettext', 'bw_gettext', 20, 3);
function bw_gettext($translated_text, $original_text, $domain) {
	if($original_text == '%1$s %2$d') {
		$translated_text = '%2$s.%1$02d';
	}
	return $translated_text;
}

月が1桁だった場合、2桁の0埋めした文字列に置き換えています。

月別アーカイブの表示形式を「July 2021」に変更

/* 月別アーカイブの表示形式を「July 2021」に変更
---------------------------------------------------------- */
//表示形式を「07 2021」に変更
function bw_gettext($translate, $original_text, $domain) {
	if($original_text == '%1$s %2$d') {
		$translate = '%1$02d月 %2$s';
	}
	return $translate;
}
add_filter('gettext', 'bw_gettext', 20, 3);

//月を英語表記に変更
function bw_get_archives_link($month) {
	$month = str_replace('01月', 'January', $month);
	$month = str_replace('02月', 'February', $month);
	$month = str_replace('03月', 'March', $month);
	$month = str_replace('04月', 'April', $month);
	$month = str_replace('05月', 'May', $month);
	$month = str_replace('06月', 'June', $month);
	$month = str_replace('07月', 'July', $month);
	$month = str_replace('08月', 'August', $month);
	$month = str_replace('09月', 'September', $month);
	$month = str_replace('10月', 'October', $month);
	$month = str_replace('11月', 'November', $month);
	$month = str_replace('12月', 'December', $month);
	return $month;
}
add_filter('get_archives_link', 'bw_get_archives_link');

まず表示形式を「2021年7月」から「07 2021」に変更します。

そして数字表記の月を英語表記に変更するわけですが、数字が1桁表記のままだと11月の「1月」の部分が「January」に置き換えられてしまうため、2桁表記にして回避しています。

まとめ

以上、WordPressの月別アーカイブの表示形式を変更する方法でした。

なお多言語対応サイトで英語表記にしたい場合は、翻訳ファイルを作成するなどして対応した方がよいかと思います。

上記の方法だと、言語ごとに表記を切り替えることはできません。