📜  wordpress 中帖子类型的子菜单 - PHP (1)

📅  最后修改于: 2023-12-03 15:06:00.613000             🧑  作者: Mango

WordPress 中帖子类型的子菜单 - PHP

WordPress 帖子类型(Post Types)是用于在 WordPress 中创建不同类型内容的机制。WordPress 默认提供了四种类型的帖子类型:帖子(Post)、页面(Page)、附件(Attachment)以及自定义菜单(Menu)。但是,有时候我们需要为我们的特定需求创建自定义的帖子类型,并将其添加到 WordPress 后台菜单中。本文将介绍如何使用 PHP 代码为 WordPress 添加自定义帖子类型的子菜单。

步骤一:定义自定义帖子类型

在 functions.php 文件中添加以下代码来定义自定义帖子类型:

function create_custom_post_type() {
    register_post_type('book',
        array(
            'labels' => array(
                'name' => __('Books'),
                'singular_name' => __('Book')
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail', 'custom-fields')
        )
    );
}
add_action('init', 'create_custom_post_type');

此代码将创建一个名为“book”的自定义帖子类型,该类型包含标题、编辑器、缩略图和自定义字段的支持。

步骤二:将自定义帖子类型添加到 WordPress 后台菜单中

接下来,使用以下代码将自定义帖子类型添加到 WordPress 后台菜单中:

function add_custom_post_type_to_menu() {
    global $submenu;
    $permalink_structure = get_option('permalink_structure');
    $menu_slug = ($permalink_structure ? 'edit.php?post_type=book' : 'edit.php?post_type=book');
    $submenu['edit.php'][20] = array($menu_slug, __('Books'), __('Books'), 'edit_posts', 'edit.php?post_type=book');
}
add_action('admin_menu', 'add_custom_post_type_to_menu');

此代码将在 WordPress 后台菜单中添加名为“Books”的子菜单,该菜单链接至包含所有自定义帖子类型帖子的页面。

完整代码
function create_custom_post_type() {
    register_post_type('book',
        array(
            'labels' => array(
                'name' => __('Books'),
                'singular_name' => __('Book')
            ),
            'public' => true,
            'has_archive' => true,
            'supports' => array('title', 'editor', 'thumbnail', 'custom-fields')
        )
    );
}
add_action('init', 'create_custom_post_type');

function add_custom_post_type_to_menu() {
    global $submenu;
    $permalink_structure = get_option('permalink_structure');
    $menu_slug = ($permalink_structure ? 'edit.php?post_type=book' : 'edit.php?post_type=book');
    $submenu['edit.php'][20] = array($menu_slug, __('Books'), __('Books'), 'edit_posts', 'edit.php?post_type=book');
}
add_action('admin_menu', 'add_custom_post_type_to_menu');

以上便是如何为 WordPress 添加自定义帖子类型的子菜单的完整代码。通过这些代码,您可以创建自己的自定义帖子类型并将其添加到 WordPress 后台菜单中,以便更好地组织您的内容。