在WordPress插件中,如何使用 register_taxonomy() 和 register_post_type() 创建自定义分类和文章类型?

2024-12-09 101 0

要在WordPress中创建自定义分类(taxonomy)和文章类型(post type),你需要使用 register_taxonomy()register_post_type() 函数。以下是如何使用这些函数的步骤和示例代码。

步骤 1: 创建自定义文章类型

首先,你需要创建一个自定义文章类型。这可以通过 register_post_type() 函数来完成。

function create_custom_post_type() {
    $labels = array(
        'name'                  => _x( 'Books', 'Post Type General Name', 'textdomain' ),
        'singular_name'         => _x( 'Book', 'Post Type Singular Name', 'textdomain' ),
        'menu_name'             => __( 'Books', 'textdomain' ),
        // ... 其他标签可以按需添加
    );

    $args = array(
        'label'                 => __( 'Books', 'textdomain' ),
        'description'           => __( 'Book custom post type', 'textdomain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'thumbnail', 'custom-fields' ),
        'taxonomies'            => array( 'category', 'post_tag' ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'post',
    );

    register_post_type( 'book', $args );
}
add_action( 'init', 'create_custom_post_type', 0 );

步骤 2: 创建自定义分类

接下来,你可以创建一个自定义分类来组织你的文章类型。

function create_custom_taxonomy() {
    $labels = array(
        'name'              => _x( 'Genres', 'Taxonomy General Name', 'textdomain' ),
        'singular_name'     => _x( 'Genre', 'Taxonomy Singular Name', 'textdomain' ),
        'search_items'      => __( 'Search Genres', 'textdomain' ),
        'all_items'         => __( 'All Genres', 'textdomain' ),
        // ... 其他标签可以按需添加
    );

    $args = array(
        'labels'            => $labels,
        'hierarchical'      => true,
        'public'            => true,
        'show_ui'           => true,
        'show_admin_column' => true,
        'show_in_nav_menus' => true,
        'show_tagcloud'     => true,
    );

    register_taxonomy( 'genre', array( 'book' ), $args );
}
add_action( 'init', 'create_custom_taxonomy', 0 );

在上面的代码中,'book' 是我们在第一步中创建的自定义文章类型的名称。现在,我们已经创建了一个名为 "Books" 的文章类型和一个名为 "Genres" 的分类。

确保将上述代码放入你的主题的 functions.php 文件中,或者创建一个插件来包含这些代码。在WordPress中激活你的主题或插件后,你应该能够在后台看到新的文章类型和分类。

相关文章

如何在WordPress插件中使用ajax?
如何通过WordPress函数创建自定义菜单?
在WordPress主题开发中,如何使用WP_Customize_Manager来自定义主题选项?
如何使用WordPress的filter钩子修改输出内容?
如何使用WordPress的action钩子添加自定义JavaScript?
在WordPress插件中,如何使用自定义表单和nonce字段来增强安全性?