将自定义帖子类型放置在现有父页面的子菜单中
根据 Codex,这是已知且预期的行为:
注意:当使用“某些字符串”显示为插件创建的菜单页面的子菜单时,该项目将成为第一个子菜单项,并替换顶级链接的位置.
Source: https://codex.wordpress.org/Function_Reference/register_post_type#Arguments(请参阅“在菜单中显示”部分)
以下是引用的结尾,它提供了解决方案:
如果不需要,创建菜单页面的插件需要将 admin_menu 的 add_action 优先级设置为 9 或更低。
所以这个问题解决起来非常简单。但是,就我而言,我无法更改父页面的优先级,因为它是由第三方库生成的。因此我想出了这个解决方案:
// Move the "example_cpt" Custom-Post-Type to be a submenu of the "example_parent_page_id" admin page.
add_action('admin_menu', 'fix_admin_menu_submenu', 11);
function fix_admin_menu_submenu() {
// Add "Example CPT" Custom-Post-Type as submenu of the "Example Parent Page" page
add_submenu_page('example_parent_page_id', 'Example CPT', 'Example CPT', 'edit_pages' , 'edit.php?post_type=example_cpt');
}
请注意优先级 11,并且在注册 Custom-Post-Type 时我设置了“show_in_menu
“参数为false
,所以我们可以通过手动将其添加到菜单中add_submenu_page
如上图所示。
正确地将 Custom-Post-Type 子菜单条目设置为“活动”
现在,上述解决方案工作正常,但是当创建/编辑“example_cpt”自定义帖子类型的帖子时,它没有设置为活动状态,并且子菜单也没有展开。以下是如何确保在创建/编辑“example_cpt”自定义帖子类型的帖子时将其设置为活动状态以及将其所在的子菜单正确设置为活动状态:
// Set the "example_parent_page_id" submenu as active/current when creating/editing a "example_cpt" post
add_filter('parent_file', 'fix_admin_parent_file');
function fix_admin_parent_file($parent_file){
global $submenu_file, $current_screen;
// Set correct active/current menu and submenu in the WordPress Admin menu for the "example_cpt" Add-New/Edit/List
if($current_screen->post_type == 'example_cpt') {
$submenu_file = 'edit.php?post_type=example_cpt';
$parent_file = 'example_parent_page_id';
}
return $parent_file;
}
微调:重命名第一个子菜单条目
此外,我还希望子菜单的第一个菜单项的名称与父名称不同。默认情况下,使用上面的代码,这就是我们所拥有的:
- Example Parent Page
-- Example Parent Page
-- Example CPT
正如您所看到的,子菜单的第一个菜单条目是父菜单的重复项,这是默认的 WordPress 行为。我想将此重复条目重命名为不同的名称,就像 WordPress 使用默认菜单所做的那样(例如“帖子”和子菜单条目“所有帖子”,它们都指向同一页面,但名称不同)。
以下是重命名第一个子菜单条目的方法:
add_action('admin_menu', 'rename_first_submenu_entry', 11);
function rename_first_submenu_entry() {
// Rename first submenu entry (duplicate of parent menu) from "Example Parent Page" to "Submenu Text"
add_submenu_page('example_parent_page_id', 'Example Parent Page', 'Submenu Text', 'edit_pages' , 'example_parent_page_id');
}
请注意优先级11,所以改名了after它已经被创建了。现在我们有:
- Example Parent Page
-- Submenu Text
-- Example CPT
请注意,“子菜单文本”指向与“示例父页面”相同的位置。