两个自定义帖子类型共享同一类别

sta*_*guy 6 wordpress

是否可以为多个自定义帖子类型添加相同的类别?

例如,

优惠券发布类型 - 交易发布类型 - 两者应该共享共同的类别,例如健康、旅行等。

但是,当我们创建新的帖子类型时,看起来我们还需要提供自定义类别。

您知道如何在没有自定义类别的情况下创建自定义帖子类型吗?

adm*_*ajn 8

是的,自定义帖子类型可以有多个分类法(类别、标签、自定义)。

是的,您可以拥有没有分类的自定义帖子类型。

将类别添加到自定义帖子类型的操作如下:

'taxonomies'          => [ 'category' ], // <--- add this (or use 'post_tag' to add tags to the CPT)
'public'              => true,
'show_ui'             => true,
'exclude_from_search' => true,
'hierarchical'        => true,
'supports'            => [
    'title', 
    'editor', 
    'thumbnail',
],
'query_var'           => true,
Run Code Online (Sandbox Code Playgroud)

如果您想为多种帖子类型添加自定义分类法,您可以执行以下操作:

function people_init() {
    // create a new taxonomy
    register_taxonomy(
        'people', [ // <-- 'people' taxo added to posts, pages, & custom_post_type
            'post', 
            'page', 
            'custom_post_type',
        ],
        array(
            'label'        => __( 'People' ),
            'rewrite'      => [
                'slug'     => 'person',
            ],
            'capabilities' => [
                'assign_terms' => 'edit_guides',
                'edit_terms'   => 'publish_guides',
            ]
        )
    );
}
add_action( 'init', 'people_init' );
Run Code Online (Sandbox Code Playgroud)