如何让wp_get_archives('type=monthly')不显示当前月份
WordPress月度归档排除当前月份实现方案
原归档调用代码为:wp_get_archives('type=monthly')
需求为在“往期通讯”页面的归档列表中隐藏当前月份,仅保留历史月份归档,当前月份内容单独在“本月通讯”页面展示,可通过以下方法实现:
- 方法1:使用WordPress原生过滤器修改归档查询条件(推荐,无需修改原有归档调用代码)
将以下代码添加到当前主题的functions.php文件中即可:
// 往期通讯页面归档排除当前月份 add_filter( 'getarchives_where', 'custom_exclude_current_month_archive', 10, 2 ); function custom_exclude_current_month_archive( $where, $args ) { // 仅在“往期通讯”页面生效,可根据实际页面情况替换判断条件:支持is_page(页面ID/页面slug/页面标题)、is_page_template(模板路径)等 if ( is_page('往期通讯') ) { // 按站点设置的时区获取当月第一天的起始时间 $current_month_start = date( 'Y-m-01 00:00:00', current_time('timestamp') ); // 追加查询条件:仅返回当月第一天之前发布的内容对应的月份归档 $where .= " AND post_date < '{$current_month_start}'"; } return $where; }
注意:不要直接使用PHP原生
time()函数获取时间,否则会因为服务器时区和站点设置时区不一致导致月份判断错误。
代码添加完成后,往期通讯页面原有的wp_get_archives('type=monthly')调用无需修改,输出时会自动过滤掉当前月份的归档项,不会影响网站其他位置的归档组件显示。
- 方法2:“本月通讯”页面单独调用当前月份文章
当前月份的文章不需要走归档逻辑,直接使用时间查询参数获取即可,参考代码如下:
// 获取站点时区下的当前年、月 $current_year = date( 'Y', current_time('timestamp') ); $current_monthnum = date( 'n', current_time('timestamp') ); // 查询当前月份发布的所有文章 $current_posts = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => -1, 'ignore_sticky_posts' => 1, 'date_query' => array( array( 'year' => $current_year, 'month' => $current_monthnum ) ) ) ); // 后续按常规WordPress循环逻辑输出文章列表即可
内容的提问来源于stack exchange,提问作者Sourav Verma
相关产品推荐
相关产品推荐

