我在
podcast_episode
中注册了一个名为 functions.php
的自定义帖子类型。
我还准备了一个模板,名为
single-podcast_episode.php
当我创建新的
podcast_episode
帖子时,经典帖子编辑器会选择 Default
模板。如果我单击下拉菜单,我可以看到我的 single-podcast_episode
模板。
如何设置才能使
single-podcast_episode
模板成为 podcast_episode
帖子的默认模板?
即如何更改自定义帖子类型的默认模板?
我本以为根据自定义帖子类型模板文件文档,我的
single-podcast_episode.php
的模板层次结构就足够了,尽管也许这只适用于前端?
根据需要创建自定义帖子类型代码:
function _s_create_custom_post_types() {
register_post_type(
'podcast_episode',
array(
'labels' => array(
'name' => __('Podcast Episodes'),
'singular_name' => __('Podcast Episode'),
'add_new' => __('Add New'),
'add_new_item' => __('Add New Podcast Episode'),
'view_item' => __('View Item'),
'edit_item' => __('Edit Item'),
'search_items' => __('Search Items'),
'not_found' => __('Not Found'),
'not_found_in_trash' => __('Not Found in Trash')
),
'public' => true,
'hierarchical' => true,
'supports' => array('title', 'editor'),
'rewrite' => array(
'slug' => 'podcast/%taxonomy_name%',
),
'taxonomies' => array('podcast_episode'),
'query_var' => true,
'supports' => array('title', 'editor', 'thumbnail'),
)
);
}
add_action('init', '_s_create_custom_post_types');
如果下拉菜单已显示
single-podcast_episode
模板,您可以将以下代码添加到 functions.php
文件中以更改默认模板选择。
/**
* When the post type is `podcast_episode`, if the current template is still `default` or not set,
* automatically assign the template `single-podcast_episode`.
*/
function set_default_template_for_podcast_episode( $post_id, $post, $update ) {
// Prevent execution during autosave or for irrelevant post types
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) {
return;
}
if ( 'podcast_episode' !== get_post_type($post_id) ) {
return;
}
// Check the current template setting
$current_template = get_post_meta($post_id, '_wp_page_template', true);
if ( ! $current_template || 'default' === $current_template ) {
update_post_meta($post_id, '_wp_page_template', 'single-podcast_episode');
}
}
add_action( 'save_post', 'set_default_template_for_podcast_episode', 10, 3 );