下面是一个详细的WordPress文章筛选应用实例代码,实现了多条件多重字段筛选功能,供参考:
- 在主题的functions.php文件中添加以下代码,创建文章筛选表单并处理用户提交的筛选条件:
/**
* 添加文章筛选表单
*/
function custom_filter_form() {
?>
<form action="<?php echo esc_url(home_url('/')); ?>" method="get">
<div class="filter-item">
<label for="author">作者:</label>
<input type="text" name="author" id="author" value="<?php echo isset($_GET['author']) ? esc_attr($_GET['author']) : ''; ?>">
</div>
<div class="filter-item">
<label for="category">分类:</label>
<?php wp_dropdown_categories(array('name' => 'category', 'selected' => isset($_GET['category']) ? $_GET['category'] : '')); ?>
</div>
<div class="filter-item">
<label for="tag">标签:</label>
<?php wp_dropdown_categories(array('taxonomy' => 'post_tag', 'name' => 'tag', 'selected' => isset($_GET['tag']) ? $_GET['tag'] : '')); ?>
</div>
<div class="filter-item">
<label for="year">年份:</label>
<select name="year" id="year">
<option value="">全部</option>
<?php
$years = get_years_with_posts(); // 获取有文章的年份列表
foreach ($years as $year) {
printf('<option value="%s" %s>%s</option>', $year, isset($_GET['year']) && $_GET['year'] == $year ? 'selected' : '', $year);
}
?>
</select>
</div>
<div class="filter-item">
<button type="submit">筛选</button>
</div>
</form>
<?php
}
/**
* 获取有文章的年份列表
*/
function get_years_with_posts() {
global $wpdb;
$years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date DESC");
return $years;
}
- 在主题的archive.php或index.php文件中,在文章循环之前添加以下代码:
<?php
if (isset($_GET['author']) || isset($_GET['category']) || isset($_GET['tag']) || isset($_GET['year'])) {
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
'author_name' => isset($_GET['author']) ? sanitize_text_field($_GET['author']) : '',
'category_name' => isset($_GET['category']) ? sanitize_text_field($_GET['category']) : '',
'tag' => isset($_GET['tag']) ? sanitize_text_field($_GET['tag']) : '',
'date_query' => array(
array(
'year' => isset($_GET['year']) ? intval($_GET['year']) : ''
)
)
);
$query = new WP_Query($args);
} else {
$query = $wp_query;
}
?>
上述代码通过检查$_GET数组是否存在特定的筛选条件,构建了一个WP_Query对象,用于获取符合条件的。
还没有评论呢,快来抢沙发~