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


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判定を短絡させるフィルタである。