2
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 3 years have passed since last update.

[WordPress]記事が存在しない月別アーカイブを404にしない

Posted at

WordPressでは記事が1件も無い月のアーカイブは404となるが、
date.phpやarchive.phpを用いて記事が無い旨を表示したい場合がある。

そのような場合はfunctions.phpに概ね以下のようなコードを書けば良い。

functions.php
<?php
function enabled_empty_date_archive_pre_handle_404($value) {
	if($value === false) {
		// 指定された年月が未来でなければ404としない
		if((is_year() || is_month()) && !is_paged()) {
			$year = get_query_var('year', 0);
			$month = get_query_var('monthnum', 0);

			$current_year = intval(date('Y'));
			if($year !== 0 && $year <= $current_year) {
				if($month !== 0) {
					$current_month = intval(date('n'));
					if($month <= $current_month || $year < $current_year) {
						$value = true;
					}
				} else {
					$value = true;
				}
			}
		}
	}
	return $value;
}
add_filter('pre_handle_404', 'enabled_empty_date_archive_pre_handle_404');

なおpre_handle_404は、false以外を返すことでページ遷移時の404判定を短絡させるフィルタである。

2
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
2
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?