要为同一帖子类型显示不同的模板,我需要创建两个不同的链接,检查我当前所在的链接,并决定加载哪个模板。
工作示例:
/**
* Register event post type
*
* Registering event post type will add such a permalink structure event/([^/]+)/?$
*/
function wpse_288345_register_event_post_type() {
$labels = array(
\'name\' => __( \'Events\' ),
\'singular_name\' => __( \'Event\' ),
\'add_new\' => __( \'Add new\' ),
\'add_new_item\' => __( \'Add new\' ),
\'edit_item\' => __( \'Edit\' ),
\'new_item\' => __( \'New\' ),
\'view_item\' => __( \'View\' ),
\'search_items\' => __( \'Search\' ),
\'not_found\' => __( \'Not found\' ),
\'not_found_in_trash\' => __( \'Not found Events in trash\' ),
\'parent_item_colon\' => __( \'Parent\' ),
\'menu_name\' => __( \'Events\' ),
);
$args = array(
\'labels\' => $labels,
\'hierarchical\' => false,
\'supports\' => array( \'title\', \'page-attributes\' ),
\'taxonomies\' => array(),
\'public\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'show_in_nav_menus\' => false,
\'publicly_queryable\' => true,
\'exclude_from_search\' => false,
\'has_archive\' => true,
\'query_var\' => true,
\'can_export\' => true,
\'rewrite\' => array(\'slug\' => \'event\'),
\'capability_type\' => \'post\',
);
register_post_type( \'event\', $args );
}
add_action( \'init\', \'wpse_288345_register_event_post_type\' );
/**
* Add custom rewrite rule for event post type.
*
* Remember to flush rewrite rules to apply changes.
*/
function wpse_288345_add_event_rewrite_rules() {
/**
* Custom rewrite rules for one post type.
*
* We wil know on which url we are by $_GET parameters \'performers\' and \'summary\'. Which we will add to
* public query vars to obtain them in convinient way.
*/
add_rewrite_rule(\'event/performers/([^/]+)/?$\', \'index.php?post_type=event&name=$matches[1]&performers=1\', \'top\');
add_rewrite_rule(\'event/summary/([^/]+)/?$\', \'index.php?post_type=event&name=$matches[1]&summary=1\', \'top\');
}
add_action(\'init\', \'wpse_288345_add_event_rewrite_rules\');
/**
* Add \'performers\' and \'summary\' custom event query vars.
*/
function wpse_288345_register_event_query_vars( $vars ) {
$vars[] = \'performers\';
$vars[] = \'summary\';
return $vars;
}
add_filter( \'query_vars\', \'wpse_288345_register_event_query_vars\' );
/**
* Decide which template to load
*/
function wpse_288345_load_performers_or_summary_template( $template ) {
// Get public query vars
$performers = (int) get_query_var( \'performers\', 0 );
$summary = (int) get_query_var( \'summary\', 0 );
// If performer = 1 then we are on event/performers link
if( $performers === 1 ) {
$template = locate_template( array( \'single-event-performers.php\' ) );
}
// If summary = 1 then we are on event/summary link
if( $summary === 1 ) {
$template = locate_template( array( \'single-event-summary.php\' ) );
}
if($template == \'\') {
throw new \\Exception(\'No template found\');
}
return $template;
}
add_filter( \'template_include\', \'wpse_288345_load_performers_or_summary_template\' );