wp_get_archives
でのアーカイブリスト、get_the_date
での投稿日取得を和暦に対応させるためのスニペットです。テーマの functions.php
にコピペしておくと使えると思います。get_the_date
については、ループ内で get_the_date( 'ja' )
とすると和暦が表示されます。
/**
* @param string $ymd Ymd format date, e.g. 20190501
* @param int|string $year
* @return array array( 'era', 'year' )
*/
function get_ja_era( $ymd, $year ) {
$year = (int) $year;
if ( $ymd <= '19120729' ) {
$era = '明治';
$year_ja = $year - 1867;
} elseif ( $ymd >= '19120730' && $ymd <= '19261224' ) {
$era = '大正';
$year_ja = $year - 1911;
} elseif ( $ymd >= '19261225' && $ymd <= '19890107' ) {
$era = '昭和';
$year_ja = $year - 1925;
} elseif ( $ymd >= '19890108' && $ymd <= '20190430' ) {
$era = '平成';
$year_ja = $year - 1988;
} elseif ( $ymd >= '20190501' ) {
$era = '令和';
$year_ja = $year - 2018;
}
if ( $year_ja === 1 ) {
$year_ja = '元';
}
return array( 'era' => $era, 'year' => $year_ja );
}
add_filter( 'get_archives_link', function( $link_html ) {
return preg_replace_callback(
"/(\d{4})年(\d+)月/",
function( $matches ) {
$year = $matches[1];
$month = $matches[2];
$month_pad = str_pad( $month, 2, 0, STR_PAD_LEFT );
$ymd = $year . $month_pad . '31';
$ja_era = get_ja_era( $ymd, $year );
return "{$ja_era['era']}{$ja_era['year']}年{$month}月";
},
$link_html
);
} );
add_filter( 'get_the_date', function( $the_date, $d, $post ) {
if ( $d !== 'ja' ) {
return $the_date;
}
$ymd = get_post_time( 'Ymd', false, $post, true );
$year = get_post_time( 'Y', false, $post, true );
$month = get_post_time( 'n', false, $post, true );
$date = get_post_time( 'j', false, $post, true );
$ja_era = get_ja_era( $ymd, $year );
return "{$ja_era['era']}{$ja_era['year']}年{$month}月{$date}日";
}, 10, 3 );