能否在自定义文章类型分类法中添加多分类?求可行实现代码
解决自定义文章类型添加多个分类法的问题
情况1:注册自定义文章类型时直接关联多个分类法
确保代码在init钩子中执行,若使用自定义分类法需先完成注册,示例代码如下:
add_action( 'init', 'register_cpt_with_multiple_taxonomies' ); function register_cpt_with_multiple_taxonomies() { // 注册自定义分类法(若未注册过) register_taxonomy( 'topics', 'custom_post', // 对应自定义文章类型的slug array( 'label' => '话题', 'rewrite' => array( 'slug' => 'topics' ), 'hierarchical' => true, // true为层级分类,false为标签式 'show_admin_column' => true, // 后台列表显示该分类列 ) ); // 注册自定义文章类型 register_post_type( 'custom_post', array( 'labels' => array( 'name' => '自定义文章', 'singular_name' => '自定义文章' ), 'public' => true, 'has_archive' => true, 'rewrite' => array( 'slug' => 'custom-post' ), 'supports' => array( 'title', 'editor', 'thumbnail' ), // 关联多个分类法:默认分类category + 自定义分类topics 'taxonomies' => array( 'category', 'topics' ) ) ); }
情况2:给已存在的自定义文章类型添加分类法
如果自定义文章类型已注册完成,可通过register_taxonomy_for_object_type函数事后关联:
add_action( 'init', 'attach_taxonomies_to_existing_cpt' ); function attach_taxonomies_to_existing_cpt() { // 关联默认分类category到自定义文章类型custom_post register_taxonomy_for_object_type( 'category', 'custom_post' ); // 关联自定义分类topics到自定义文章类型custom_post register_taxonomy_for_object_type( 'topics', 'custom_post' ); }
排查你之前失败的常见原因
- 自定义分类法
topics未正确注册,或注册时未指定关联目标文章类型 - 代码未在
init钩子中执行,直接放在主题functions.php顶部会导致执行时机错误 - 自定义文章类型的slug拼写错误(比如注册时用
custom_post,关联时写错成custom_posts) - 修改代码后未刷新固定链接:进入WordPress后台「设置→固定链接」,直接点击保存即可刷新规则
内容的提问来源于stack exchange,提问作者Zaman Kazol
相关产品推荐
相关产品推荐

