能否在WordPress中实现按年/月/日筛选文章的自定义过滤器表单?
WordPress 自定义日期过滤器表单实现方案
核心思路
基于WordPress原生归档URL规则,通过表单提交后拼接年份、月份、日期参数,直接跳转至系统自带的归档页面,无需额外开发自定义查询逻辑。
实现步骤
1. 编写HTML表单代码
可将这段代码放入主题functions.php(通过短代码输出),或直接嵌入需要展示的页面模板:
<form method="get" action="<?php echo home_url('/'); ?>" class="date-filter-form"> <div class="filter-group"> <label for="filter-year">年份</label> <?php // 获取所有存在发布文章的年份 global $wpdb; $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC"); ?> <select name="year" id="filter-year"> <option value="">选择年份</option> <?php foreach ($years as $year) : ?> <option value="<?php echo esc_attr($year); ?>"><?php echo esc_html($year); ?></option> <?php endforeach; ?> </select> </div> <div class="filter-group"> <label for="filter-month">月份</label> <select name="monthnum" id="filter-month"> <option value="">选择月份</option> <?php for ($month = 1; $month <= 12; $month++) : ?> <option value="<?php echo esc_attr($month); ?>"><?php echo esc_html(date_i18n('F', mktime(0, 0, 0, $month, 1))); ?></option> <?php endfor; ?> </select> </div> <div class="filter-group"> <label for="filter-day">日期</label> <select name="day" id="filter-day"> <option value="">选择日期</option> <?php for ($day = 1; $day <= 31; $day++) : ?> <option value="<?php echo esc_attr($day); ?>"><?php echo esc_html($day); ?></option> <?php endfor; ?> </select> </div> <button type="submit" class="filter-submit">筛选文章</button> </form>
2. 表单跳转规则说明
表单使用get方法提交后,WordPress会自动识别参数并跳转至对应归档页:
- 仅选年份:跳转至
/YYYY/格式的年归档页 - 选择年+月:跳转至
/YYYY/MM/格式的月归档页 - 选择年+月+日:跳转至
/YYYY/MM/DD/格式的日归档页
3. 可选:添加JS校验优化体验
避免用户提交无效组合(如单独选月/日),可添加以下JavaScript:
document.querySelector('.date-filter-form').addEventListener('submit', function(e) { const year = document.getElementById('filter-year').value; const month = document.getElementById('filter-month').value; const day = document.getElementById('filter-day').value; // 校验规则:选月必须先选年,选日必须先选年和月 if ((month && !year) || (day && (!year || !month))) { e.preventDefault(); alert('请先选择年份;选择日期前,请先选择年份和月份'); } });
4. 可选:自定义表单样式
添加CSS美化布局:
.date-filter-form { display: flex; gap: 1rem; align-items: center; padding: 1rem; background: #f5f5f5; border-radius: 8px; } .filter-group { display: flex; flex-direction: column; gap: 0.3rem; } .filter-group label { font-size: 0.9rem; font-weight: 500; } .filter-group select { padding: 0.5rem; border: 1px solid #ddd; border-radius: 4px; } .filter-submit { padding: 0.5rem 1.2rem; background: #0073aa; color: white; border: none; border-radius: 4px; cursor: pointer; } .filter-submit:hover { background: #006799; }
注意事项
- 若在自定义插件中使用表单,需先声明
global $wpdb;确保变量可用 - 年份下拉框仅展示存在发布文章的年份,避免空归档情况
- 日期下拉框显示1-31,WordPress会自动处理无效日期(如2月选31日会跳转到当月最后一天的归档页)
内容的提问来源于stack exchange,提问作者Abhay Vishwakarma
相关产品推荐
相关产品推荐

