如何在WordPress子主题中修改父主题的自定义文章类型标签
修改父主题自定义文章类型(子主题实现)
要在子主题中修改父主题的release自定义文章类型,核心思路是先移除父主题的注册动作,再重新注册一个新的自定义文章类型(替换成你想要的名称)——这样既不会改动父主题的文件,也能完美实现需求。
具体步骤及代码示例:
移除父主题的自定义文章类型注册
父主题通过add_action('init', 'kentha_release_register_type')完成了release类型的注册,我们需要在子主题中把这个注册动作移除。这里要注意:必须确保移除动作在父主题的注册之后执行,所以我们给子主题的移除动作设置更高的优先级(比如11,父主题默认优先级是10)。重新注册自定义文章类型
复制父主题注册函数里的核心逻辑,把所有和release相关的标识(包括标签文本、slug、类型名称)都替换成你想要的内容——下面示例中我用project作为新名称,你可以根据自己的需求修改。
把这段代码添加到你的子主题functions.php文件中:
// 移除父主题的release自定义文章类型注册 add_action('init', 'remove_parent_release_cpt', 11); function remove_parent_release_cpt() { remove_action('init', 'kentha_release_register_type'); } // 重新注册自定义文章类型(示例替换为"project",你可以改成自己想要的名称) add_action('init', 'custom_project_register_type'); if(!function_exists('custom_project_register_type')){ function custom_project_register_type() { // 自定义新类型的标签文本,按需修改 $labels = array( 'name' => _x('Projects', 'Post Type General Name', 'your-child-theme-textdomain'), 'singular_name' => _x('Project', 'Post Type Singular Name', 'your-child-theme-textdomain'), 'menu_name' => __('Projects', 'your-child-theme-textdomain'), 'name_admin_bar' => __('Project', 'your-child-theme-textdomain'), 'add_new' => __('Add New', 'your-child-theme-textdomain'), 'add_new_item' => __('Add New Project', 'your-child-theme-textdomain'), 'new_item' => __('New Project', 'your-child-theme-textdomain'), 'edit_item' => __('Edit Project', 'your-child-theme-textdomain'), 'view_item' => __('View Project', 'your-child-theme-textdomain'), 'all_items' => __('All Projects', 'your-child-theme-textdomain'), 'search_items' => __('Search Projects', 'your-child-theme-textdomain'), 'parent_item_colon' => __('Parent Projects:', 'your-child-theme-textdomain'), 'not_found' => __('No projects found.', 'your-child-theme-textdomain'), 'not_found_in_trash' => __('No projects found in Trash.', 'your-child-theme-textdomain') ); // 配置新类型的参数,重点替换slug和类型名称 $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_in_menu' => true, 'query_var' => true, 'rewrite' => array('slug' => 'project'), // 替换为新的URL slug 'capability_type' => 'post', 'has_archive' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array('title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments'), // 这里可以保留父主题原来的其他参数,或者根据需求调整 ); register_post_type('project', $args); // 替换为新的自定义文章类型标识 } }
关键注意事项:
- 把
your-child-theme-textdomain替换成你的子主题文本域(如果没设置过,也可以用父主题的文本域,或者直接留空)。 - 完全根据你的需求修改
$labels里的文本和$args中的配置项,确保和你想要的名称、功能匹配。 - 代码添加完成后,一定要去WordPress后台的设置→固定链接页面,直接点击保存按钮刷新固定链接规则,这样新的URL slug才能生效。
这样操作后,原来父主题的release自定义文章类型就会被替换成你设置的新类型啦!
内容的提问来源于stack exchange,提问作者Massimo Salerno
相关产品推荐
相关产品推荐

