自定义帖子类型可以有页面等模板选项,但有点复杂,但我将尝试解释一下:
1) you need to register a new meta box with a drop down (custom meta field) of all the templates:
function register_post_cookingrecipes() {
add_meta_box(\'cookingrecipes-details\', __(\'Template Details\'), \'add_cookingrecipes_meta_box\', \'cookingrecipes\', \'side\', \'high\');
if ((\'delete_posts\'))
add_action(\'delete_post\', \'delete_meta_cookingrecipes\', 10);
}
add_action(\'admin_init\', \'register_post_cookingrecipes\', 1);
function add_cookingrecipes_meta_box($post) {
$page_template = get_post_meta($post->ID, \'_wp_page_template\', TRUE);
?>
<label for="page_template"><?php _e(\'Template\') ?>: </label><br/>
<select style="width:100%" name="page_template" id="page_template">
<option value=\'single-cookingrecipes.php\'><?php _e(\'Default\'); ?></option>
<option <?php if ($page_template === \'single-cookingrecipes-fullwidth.php\') echo \'selected="selected"\'; ?> value=\'single-cookingrecipes-fullwidth.php\'>full width</option>
</select>
<?php
}
2) Save/Delete the content of the new meta field when the post saved.
function save_cookingrecipes_meta($post_id) {
$post = $_POST[\'post_type\'];
if (defined(\'DOING_AUTOSAVE\') && DOING_AUTOSAVE)
return;
if (!current_user_can(\'edit_page\', $post_id))
return;
switch ($post) {
case \'cookingrecipes\':
$page_template = $_POST[\'page_template\'];
if (!empty($page_template))
update_post_meta($post_id, \'_wp_page_template\', $page_template);
break;
default:
return;
}
}
add_action(\'save_post\', \'save_cookingrecipes_meta\');
function delete_meta_cookingrecipes($post_id) {
$post = $_POST[\'post_type\'];
switch ($post) {
case \'cookingrecipes\':
delete_post_meta($post_id, \'_wp_page_template\');
break;
default:
return;
}
}
3) The key part for loading the custom template you created is here
function cookingrecipes_template_redirect() {
global $post;
$queried_post_type = get_query_var(\'post_type\');
if (is_single() && \'cookingrecipes\' == $queried_post_type) {
$page_template = get_post_meta($post->ID, \'_wp_page_template\', TRUE);
if ($page_template !== \'\' && isset($page_template)) {
include(get_stylesheet_directory() . \'/\' . $page_template);
exit;
}
}
}
add_action("template_redirect", \'cookingrecipes_template_redirect\');
有任何问题,请告诉我