步骤1,为自定义事件年和月查询变量添加重写标记,然后在重写参数的slug参数中使用这些标记注册事件post类型:
function wpa83531_register_event_post_type(){
add_rewrite_tag(\'%event_year%\',\'(\\d+)\');
add_rewrite_tag(\'%event_month%\',\'(.+)\');
register_post_type( \'event\',
array(
\'public\' => true,
\'rewrite\' => array( \'slug\' => \'events/%event_year%/%event_month%\' ),
\'has_archive\' => false,
\'hierarchical\' => false,
\'supports\' => array(\'custom-fields\', \'title\', \'editor\')
)
);
}
add_action( \'init\', \'wpa83531_register_event_post_type\' );
步骤2,过滤帖子类型链接,用自定义字段中的值替换这些标记
event_year
和
event_month
. 如果自定义字段不存在,则会插入一些默认值,以便您至少可以预览帖子而不会出错:
function wpa83531_event_post_link( $permalink, $post, $leavename ) {
if ( stripos( $permalink, \'%event_year%\' ) == false )
return $permalink;
if ( is_object( $post ) && \'event\' == $post->post_type ) {
$default_year = \'1970\';
$default_month = \'january\';
if( $event_year = get_post_meta( $post->ID, \'event_year\', true ) ){
$permalink = str_replace( \'%event_year%\', $event_year, $permalink );
} else {
$permalink = str_replace( \'%event_year%\', $default_year, $permalink );
}
if( $event_month = get_post_meta( $post->ID, \'event_month\', true ) ){
$permalink = str_replace( \'%event_month%\', $event_month, $permalink );
} else {
$permalink = str_replace( \'%event_month%\', $default_month, $permalink );
}
}
return $permalink;
}
add_filter( \'post_type_link\', \'wpa83531_event_post_link\', 10, 3 );