假设事件重写slug是event,并且希望基于日期的URL如下所示:http://domain.com/event/2011-06-14/
function custom_permalink_for_my_cpt( $rules ) {
$custom_rules = array();
// a rewrite rule to add our custom date based urls
$custom_rules[\'event/([0-9]{4}-[0-9]{2}-[0-9]{2})/?$\'] = \'index.php?post_type=event&event-date=$matches[1]\';
return $custom_rules + $rules;
}
add_filter( \'rewrite_rules_array\', \'custom_permalink_for_my_cpt\' );
// add a query var so we can read the date passed in url
function my_custom_query_vars( $query_vars ) {
$query_vars[] = \'event-date\';
return $query_vars;
}
add_filter( \'query_vars\', \'my_custom_query_vars\' );
// modify the main wordpress query
function my_date_based_event_archives() {
// only modify the wordpress query if its event archive and
// we have got the event-date passed through the url
if ( is_archive( \'event\' ) && get_query_var( \'event-date\' ) ) {
global $wp_query;
$meta_query = array(
\'meta_query\' => array(
array(
\'key\' => \'event-date\',
\'value\' => get_query_var( \'event-date\' )
)
)
);
$args = array_merge( $wp_query->query, $meta_query );
query_posts( $args );
}
}
add_action( \'get_template_part_loop\', \'my_date_based_event_archives\' );