不久前我为一个客户做了类似的事情,我将在这里给您一些代码,您可以根据自己的需要进行调整。我要警告你,这很难理解!
首先,我设置了一些自定义重写规则来获取年/月URL结构,并设置了一些查询变量来将年和月传递给我的模板。在这个例子中,我用slug设置了一个页面event-calendar
我将其用作我的事件列表/归档页面。该代码将进入functions.php
:
<?php
add_action( \'init\', \'wpse_rewrites_init\' );
function wpse_rewrites_init(){
// after adding, visit settings > permalinks to flush rewrite rules!
add_rewrite_rule(
\'event-calendar/([0-9]+)/([0-9]+)/?$\',
\'index.php?pagename=event-calendar&wpse_year=$matches[1]&wpse_month=$matches[2]\',
\'top\' );
add_rewrite_rule(
\'event-calendar/([0-9]+)/?$\',
\'index.php?pagename=event-calendar&wpse_year=$matches[1]\',
\'top\' );
}
add_filter( \'query_vars\', \'wpse_query_vars\' );
function wpse_query_vars( $query_vars ){
$query_vars[] = \'wpse_year\';
$query_vars[] = \'wpse_month\';
return $query_vars;
}
这是我的
page-event-calendar.php
用于根据年和月(如果已设置)查询事件的模板,否则我只显示即将发生的事件:
<?php
// default args, upcoming events
$args = array(
\'posts_per_page\' => -1,
\'meta_key\' => \'event_date\',
\'meta_value\' => date(\'Y-m-d\'),
\'meta_compare\' => \'>=\',
\'orderby\' => \'meta_value\',
\'order\' => \'ASC\'
);
// get the year and month query vars
$wpse_year = get_query_var(\'wpse_year\');
$wpse_month = get_query_var(\'wpse_month\');
// if a month was set we query for the requested month/year (we assume year is set if month is)
if($wpse_month):
$estart = $wpse_year.\'-\'.$wpse_month.\'-01\';
$eend = $wpse_year.\'-\'.$wpse_month.\'-31\';
$args = array(
\'posts_per_page\' => -1,
\'meta_query\' => array(
array(
\'key\' => \'event_date\',
\'value\' => array( $estart, $eend ),
\'compare\' => \'BETWEEN\',
\'type\' => \'date\',
)
),
\'orderby\' => \'meta_value\',
\'order\' => \'ASC\'
);
endif;
// if just a year is set, we query for the requested year
if($wpse_year&&!$wpse_month):
$estart = $wpse_year.\'-01-01\';
$eend = $wpse_year.\'-12-31\';
$args = array(
\'posts_per_page\' => -1,
\'meta_query\' => array(
array(
\'key\' => \'event_date\',
\'value\' => array( $estart, $eend ),
\'compare\' => \'BETWEEN\',
\'type\' => \'date\',
)
),
\'orderby\' => \'meta_value\',
\'order\' => \'ASC\'
);
endif;
// query for our events
$events = new WP_Query($args);
while($events->have_posts()) : $events->the_post();
// do your normal loop stuff here
endwhile;
为了输出过去事件的年/月归档列表,我使用一些自定义SQL来获取
event_date
钥匙这比与实际帖子进行连接要快,但缺点是你可能会得到未发布帖子的元数据。这可以满足我客户的需求,但可能不是你的需求。
$query = "SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = \'event_date\' AND DATE(meta_value) < DATE(NOW()) ORDER BY meta_value DESC";
$all_unique_dates = $wpdb->get_results($query);
您可以删除
AND DATE(meta_value) < DATE(NOW()
如果希望将来的事件也在列表中,请设置条件。
好了,就这样!希望你能找到一些有用的东西。