Loading... ```php <?php /** * Demo: Create Hierarchical Taxonomy Terms for Custom Post Type * This script registers a custom post type and taxonomy, then auto-creates categories. */ function demo_register_product_post_type() { register_post_type('product', [ 'label' => 'Products', 'public' => true, 'has_archive' => true, 'supports' => ['title', 'editor', 'thumbnail'], 'show_in_rest' => true, ]); register_taxonomy('product_cat', 'product', [ 'label' => 'Product Categories', 'hierarchical' => true, 'rewrite' => ['slug' => 'product-category'], 'show_in_rest' => true, ]); } add_action('init', 'demo_register_product_post_type'); function demo_create_product_categories() { $categories = [ 'Digital Products' => [ 'slug' => 'digital-products', 'desc' => 'All kinds of digital goods.', 'children' => [ ['name' => 'E-books', 'slug' => 'ebooks', 'desc' => 'Downloadable e-books and guides.'], ['name' => 'Software', 'slug' => 'software', 'desc' => 'Apps, tools, and licenses.'], ['name' => 'Courses', 'slug' => 'courses', 'desc' => 'Online courses and workshops.'], ], ], 'Physical Goods' => [ 'slug' => 'physical-goods', 'desc' => 'Physical products and merchandise.', 'children' => [ ['name' => 'Clothing', 'slug' => 'clothing', 'desc' => 'T-shirts, hoodies, and more.'], ['name' => 'Accessories', 'slug' => 'accessories', 'desc' => 'Bags, keychains, etc.'], ], ], 'Services' => [ 'slug' => 'services', 'desc' => 'Custom services and consulting.', 'children' => [ ['name' => 'Design', 'slug' => 'design', 'desc' => 'UI/UX and graphic design services.'], ['name' => 'Development', 'slug' => 'development', 'desc' => 'Web and app development services.'], ['name' => 'Marketing', 'slug' => 'marketing', 'desc' => 'SEO and content strategy.'], ], ], ]; foreach ($categories as $parent_name => $data) { $parent_term = term_exists($data['slug'], 'product_cat'); if (!$parent_term) { $parent_term = wp_insert_term( $parent_name, 'product_cat', [ 'slug' => $data['slug'], 'description' => $data['desc'], ] ); } if (!empty($data['children']) && !is_wp_error($parent_term)) { $parent_id = $parent_term['term_id'] ?? $parent_term; foreach ($data['children'] as $child) { if (!term_exists($child['slug'], 'product_cat')) { wp_insert_term( $child['name'], 'product_cat', [ 'slug' => $child['slug'], 'description' => $child['desc'], 'parent' => $parent_id, ] ); } } } } } add_action('after_switch_theme', 'demo_create_product_categories'); ``` ``` #### 🧭 分类结构示例 * Digital Products ├─ E-books ├─ Software └─ Courses * Physical Goods ├─ Clothing └─ Accessories * Services ├─ Design ├─ Development └─ Marketing ``` 复制这个php代码到模板的`functions.php`尾部然后重新激活(切换)一下模板触发即可 最后修改:2025 年 10 月 14 日 © 允许规范转载 打赏 赞赏作者 微信 赞 0 如果觉得我的文章对你有用,请随意赞赏
此处评论已关闭