示例场景:
在首页根据自定义字段的活动日期进行排序,并排除已过去的活动
<?php
$today = date('Ymd');
$homepageEvents = new WP_Query(array(
'posts_per_page' => 2,
'post_type' => 'event',
'meta_key' => 'event_date', // 此处为自定义字段名
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
)
));
while($homepageEvents->have_posts()) {
$homepageEvents->the_post();
// loop
}
wp_reset_postdata();
在文章归档页根据自定义字段的活动日期进行排序,并排除已过去的活动,在 function.php 中修改
<?php
function event_adjust_queries($query) {
if (!is_admin() AND is_post_type_archive('event') AND $query->is_main_query) {
$today = date('Ymd');
$query->set('meta_key', 'event_date'); // 此处为自定义字段名
$query->set('orderby', 'meta_value_num');
$query->set('order', 'ASC');
$query->set('meta_query', array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
));
}
}
add_action('pre_get_posts', 'event_adjust_queries')
在页面中创建过去活动归档页,并创建页面模板,执行以下查询代码
<?php
$today = date('Ymd');
$pastEvent = new WP_Query(array(
'paged' => get_query_var('paged', 1),
'post_type' => 'event',
'meta_key' => 'event_date', // 此处为自定义字段名
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'event_date',
'compare' => '>=',
'value' => $today,
'type' => 'numeric'
)
)
));
while($pastEvent->have_posts()) {
$pastEvent->the_post();
// loop
}
echo paginate_links(array(
'total' => $pastEvents->max_num_pages
));