我已经注册了自定义重写规则query_vars
用于显示基于ISO日期格式的事件列表。例如,当用户请求URL时,http://site.com/by-date/2013-04-04/
, 我的query_var
是日期部分,我想显示一个事件列表meta_key
属于_event_scheduled_date
等于中的ISO日期值query_var
.
每当我尝试使用以下代码修改$query
在里面pre_get_posts
WordPress启动404,不查询帖子。我已经能够使用pre_get_posts
操作其他分类列表和归档页面,但尚未能够使其与自定义query_var
我已经创造了。
function rewrite_rule_by_date() {
add_rewrite_rule(\'(by\\-date)/([0-9]{4}\\-[0-9]{2}\\-[0-9]{2})$\', \'index.php?pagename=$matches[1]&event_date=$matches[2]\', \'top\');
}
add_action( \'init\', \'rewrite_rule_by_date\' );
function query_var_by_date() {
add_rewrite_tag( \'%event_date%\', \'([0-9]{4}-[0-9]{2}-[0-9]{2})\');
}
add_action( \'init\', \'query_var_by_date\' );
function custom_event_query( $query ) {
if ( is_page( \'by-date\' ) && get_query_var( \'event_date\' ) && is_main_query() ) {
$query->set( \'post_type\', \'event\' );
$query->set( \'post_status\', \'publish\' );
$query->set( \'meta_key\', \'_event_scheduled_date\' );
$query->set( \'orderby\', \'meta_value\' );
$query->set( \'order\', \'ASC\' );
$query->set( \'post_per_page\', -1 );
$meta_query = array(
array(
\'key\' => \'_event_scheduled_date\',
\'value\' => get_query_var( \'event_date\' ),
\'type\' => \'DATE\',
\'compare\' => \'=\'
)
);
$query->set( \'meta_query\', $meta_query );
}
return $query;
}
add_filter( \'pre_get_posts\', \'custom_event_query\' );
最合适的回答,由SO网友:birgire 整理而成
而不是尝试在by-date
第页,您可以尝试通过?post_type=event
像这样:
function rewrite_rule_by_date() {
add_rewrite_rule(\'by\\-date/([0-9]{4}\\-[0-9]{2}\\-[0-9]{2})$\', \'index.php?post_type=event&event_date=$matches[1]\', \'top\');
}
add_action( \'init\', \'rewrite_rule_by_date\' );
function query_var_by_date() {
add_rewrite_tag( \'%event_date%\', \'([0-9]{4}-[0-9]{2}-[0-9]{2})\');
}
add_action( \'init\', \'query_var_by_date\' );
function custom_event_query( $query ) {
if ( get_query_var( \'event_date\' ) && is_main_query() ) {
$query->set( \'post_type\', \'event\' );
$query->set( \'post_status\', \'publish\' );
$query->set( \'meta_key\', \'_event_scheduled_date\' );
$query->set( \'orderby\', \'meta_value\' );
$query->set( \'order\', \'ASC\' );
$query->set( \'post_per_page\', -1 );
$meta_query = array(
array(
\'key\' => \'_event_scheduled_date\',
\'value\' => get_query_var( \'event_date\' ),
\'type\' => \'DATE\',
\'compare\' => \'=\'
)
);
$query->set( \'meta_query\', $meta_query );
}
return $query;
}
add_filter( \'pre_get_posts\', \'custom_event_query\' );
这对我的Wordpress有效
3.5.1
使用默认的二十一主题安装,url如下:
http://example.com/by-date/2013-04-04/