像Jacob Peattie 指出in this comment, 代码不起作用的原因是您有两个同名函数create_posttype
. PHP假设您想重新声明函数,但您不能这样做。
因此,为了让代码正常工作,您可以将自定义帖子类型创建组合到一个函数中(正如Jacob所建议的):
// Our custom post type function
function create_posttype() {
register_post_type( \'articles\',
// CPT Options
array(
\'labels\' => array(
\'name\' => __( \'Articles\' ),
\'singular_name\' => __( \'Article\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'articles\'),
\'show_in_rest\' => true,
)
);
register_post_type( \'projects\',
// CPT Options
array(
\'labels\' => array(
\'name\' => __( \'Projects\' ),
\'singular_name\' => __( \'Project\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'projects\'),
\'show_in_rest\' => true,
)
);
}
// Hooking up our function to theme setup
add_action( \'init\', \'create_posttype\' );
... 或者,如果您喜欢使用两个函数,请为每个函数指定一个唯一的名称:
// Our custom post type function
function create_posttype_articles() {
register_post_type( \'articles\',
// CPT Options
array(
\'labels\' => array(
\'name\' => __( \'Articles\' ),
\'singular_name\' => __( \'Article\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'articles\'),
\'show_in_rest\' => true,
)
);
}
// Hooking up our function to theme setup
add_action( \'init\', \'create_posttype_articles\' );
// Our custom post type function
function create_posttype_projects() {
register_post_type( \'projects\',
// CPT Options
array(
\'labels\' => array(
\'name\' => __( \'Projects\' ),
\'singular_name\' => __( \'Project\' )
),
\'public\' => true,
\'has_archive\' => true,
\'rewrite\' => array(\'slug\' => \'projects\'),
\'show_in_rest\' => true,
)
);
}
// Hooking up our function to theme setup
add_action( \'init\', \'create_posttype_projects\' );