我已使用此代码创建自定义帖子类型
public static function init() {
add_action( 'init', array( __CLASS__, 'register_post_types' ), 10);
add_filter('template_include', array( __CLASS__, 'exam_template'), 1);
}
public static function register_post_types() {
$labels = array(
'name' => __( 'Exam Online', 'Edinnova' ),
'singular_name' => 'Exam',
'add_new' => 'Add New',
'add_new_item' => 'Add New '.'Exam Online',
'edit_item' => 'Edit '.'Exam Online',
'new_item' => 'New '.'Exam Online',
'all_items' => 'All '.'Exams',
'view_item' => 'View '.'Exam Online',
'search_items' => 'Search '.'Exam',
'not_found' => 'No '.'Exam'.' Found',
'not_found_in_trash' => 'No '.'Exam'.' Found In Trash',
'parent_item_colon' => '',
'menu_name' => 'Exam Online'
);
$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => false,
'query_var' => true,
'capability_type' => 'post',
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor','thumbnail','author'),
'capability_type' => 'post',
);
register_post_type( 'exam_online', $args );
add_rewrite_rule('exam_online/([^ /] +)/review', '?index.php&exam=$params[1]&review=yes', 'top');
add_filter('query_vars', function($_vars) {
$_vars[] = 'review';
return $_vars;
});
flush_rewrite_rules();
}
public static function exam_template($template) {
if (get_post_type() == 'exam_online') {
if ($_GET['review'] == 'yes') {
$single_template = dirname(__dir__).'/templates/review-exam_online.php';
}
$single_template = dirname(__dir__).'/templates/single-exam_online.php';
}
return $single_template;
}
当我创建自定义帖子然后在首页上查看时,我有这个网址<domain>/exam_online/<post-url-slug>/
URL上方将按单个模板显示
并且我希望网址<domain>/exam_online/<post-url-slug>/review
通过评论模板显示
但是可能有些问题,当我转到网址<domain>/exam_online/<post-url-slug>/review
时始终返回404。
我的代码有什么问题?请帮忙!
另一个奇怪的是,当我使用插件Debug Bar Rewrite Rules
时,wordpress似乎无法识别我的重写规则,因为当我搜索正则表达式规则时没有结果。