3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WordPress で和暦表示させる(簡易版)

Last updated at Posted at 2019-04-23

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 );
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?