简单的回答是:没有办法控制下拉列表中显示的内容,没有可用的过滤器。希望在未来的版本中会有所改变。
一个可能的解决方案是创建您自己的元框,其中列出您自己的模板数组中适合当前页面的模板,并将选择保存为post meta。然后将过滤器添加到page_template
检查该元值并加载该模板。
EDIT- 下面是一个完整的工作示例,代码改编自add_meta_box
codex page. 你唯一需要改变的是$wpa70686_custom_templates
大堆格式是要使模板可用的页面ID,然后在这些数组中是文件名(减去.php
), 以及下拉菜单中显示的名称。
// page ID, template filename, template display name
$wpa70686_custom_templates = array(
42 => array(
\'custom1\' => \'Custom Template One\',
\'custom2\' => \'Custom Template Two\',
),
96 => array(
\'custom3\' => \'Custom Template Three\',
\'custom4\' => \'Custom Template Four\',
)
);
// add the meta box
add_action( \'add_meta_boxes\', \'wpa70686_add_template_box\' );
function wpa70686_add_template_box() {
add_meta_box(
\'wpa70686_template_box\',
\'Page Template\',
\'wpa70686_render_template_box\',
\'page\',
\'side\'
);
}
// display the meta box on the apprpriate pages
function wpa70686_render_template_box( $post ) {
global $wpa70686_custom_templates;
wp_nonce_field( \'wpa70686_nonce\', \'wpa70686_noncename\' );
if( array_key_exists( $post->ID, $wpa70686_custom_templates ) ) :
$current_value = get_post_meta( $post->ID, \'_wpa70686_template\', TRUE );
echo \'<select id="wpa70686_template_box" name="wpa70686_template_box">\';
echo \'<option value="default">Default</option>\';
foreach( $wpa70686_custom_templates[$post->ID] as $template_file => $template_name ):
$selected = $current_value == $template_file ? \' selected\' : \'\';
echo \'<option value="\' . $template_file . \'"\' . $selected . \'>\' .$template_name . \'</option>\';
endforeach;
echo \'</select>\';
else:
echo \'no templates for this page\';
endif;
}
// save the meta box value if it exists
add_action( \'save_post\', \'wpa70686_save_template_box\' );
function wpa70686_save_template_box( $post_id ) {
if ( defined( \'DOING_AUTOSAVE\' ) && DOING_AUTOSAVE ) return;
if ( !wp_verify_nonce( $_POST[\'wpa70686_noncename\'], \'wpa70686_nonce\' ) ) return;
if ( \'page\' == $_POST[\'post_type\'] ){
if ( !current_user_can( \'edit_page\', $post_id ) ) return;
} else {
if ( !current_user_can( \'edit_post\', $post_id ) ) return;
}
if( isset( $_POST[\'wpa70686_template_box\'] ) ):
$new_value = $_POST[\'wpa70686_template_box\'];
$current_value = get_post_meta( $post_id, \'_wpa70686_template\', true );
if( $current_value ):
if( \'default\' == $new_value ):
delete_post_meta( $post_id, \'_wpa70686_template\' );
else:
update_post_meta( $post_id, \'_wpa70686_template\', $new_value );
endif;
else:
add_post_meta( $post_id, \'_wpa70686_template\', $new_value, true );
endif;
endif;
}
// load the custom template for pages with the meta value set
add_filter( \'page_template\', \'wpa70686_custom_template\' );
function wpa70686_custom_template(){
global $wp_query;
if ( $template = get_post_meta( $wp_query->queried_object_id, \'_wpa70686_template\', true ) )
return locate_template( $template . \'.php\' );
}