You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在后台自定义文章类型中启用页面属性的Templates功能?

如何为自定义文章类型启用页面属性中的“Templates”功能

没问题,这个问题很常见——WordPress 默认只把页面模板功能开放给原生的page文章类型,要给你自己的自定义文章类型启用这个功能,只需要两步操作就行:

1. 给自定义文章类型添加page-attributes支持

不管你是刚注册自定义文章类型,还是已经注册好了,都可以通过代码添加这个支持:

情况一:注册自定义文章类型时直接配置

如果是还没注册或者可以修改注册代码,在register_post_type()函数的supports参数里加上'page-attributes',同时建议开启show_in_rest(保证块编辑器能正常显示模板选项):

function register_my_custom_post_type() {
    $args = array(
        'labels' => array(
            'name' => '我的自定义文章',
            'singular_name' => '自定义文章'
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'page-attributes'), // 必须包含page-attributes
        'show_in_rest' => true // 适配块编辑器
    );
    register_post_type('my_custom_cpt', $args); // 替换成你的自定义文章类型slug
}
add_action('init', 'register_my_custom_post_type');

情况二:给已注册的自定义文章类型追加支持

如果已经注册好了不想动原代码,可以用add_post_type_support()函数来追加支持:

function add_template_support_to_existing_cpt() {
    add_post_type_support('my_custom_cpt', 'page-attributes'); // 替换成你的自定义文章类型slug
}
add_action('init', 'add_template_support_to_existing_cpt', 11); // 优先级设为11,确保在注册之后执行

2. 让主题模板支持你的自定义文章类型

完成第一步后,后台会显示页面属性元框,但如果主题的模板默认只支持page类型,你还需要修改模板文件的注释,让它识别你的自定义文章类型:

找到主题里你想用于自定义文章类型的模板文件(比如template-full-width.php),在文件顶部的注释里添加Template Post Type字段,把你的自定义文章类型slug加进去:

<?php
/*
Template Name: 全宽模板
Template Post Type: page, my_custom_cpt // 这里追加你的自定义文章类型slug
*/
?>

这样这个模板就会出现在自定义文章类型编辑页面的「页面属性」→「Templates」下拉菜单里了。

如果是想专门给自定义文章类型创建模板,也可以直接命名为single-{your-cpt-slug}.php或者archive-{your-cpt-slug}.php,这类模板会自动应用到对应的自定义文章类型上,不需要额外配置。

做完这两步,刷新后台的自定义文章类型编辑页面,就能看到「Templates」选项啦!

内容的提问来源于stack exchange,提问作者user136032

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:52:28