以编程方式创建类别和子类别和子类别

时间:2020-01-03 作者:Khairi Ksouri

我想插入如下类别:

A类

第1子类第2子类第3子类谢谢

这是我的密码

$term = wp_insert_term(
    $row[11], 
    \'product_cat\',
    [
        \'description\' => \'FooBar Category description\', 
        \'slug\' => $row[11]
    ]
);
if(is_wp_error($term)) {
    $term_id = $term->error_data[\'term_exists\'] ?? null;
} else {
    $term_id = $term[\'term_id\'];
}
$term1 = wp_insert_term(
    $row[12], 
    \'product_cat\', 
    array(
        // what to use in the url for term archive
        \'slug\' => $row[12], 
        // link with main category. In the case, become a child of the "Category A" parent  
        \'parent\' => term_exists($row[11], \'product_cat\')[\'term_id\']
    )
);
$term2 = wp_insert_term($row[13], \'product_cat\', 
    array(
        // what to use in the url for term archive
        \'slug\' => $row[13], 
        // link with main category. In the case, become a child of the "Category A" parent  
        \'parent\' => term_exists($row[12], \'product_cat\')[\'term_id\']
    )
);

1 个回复
SO网友:Atanas Antonov

当您尝试插入要查找的子类别时term_exists() 返回带有键的数组term_id.

遵循以下文档:term_exists

返回值

(mixed)

如果术语不存在,则返回0或NULLterm id,\'term\\u taxonomy\\u id\'=>taxonomy id))似乎缺少term_exists() 这是之前插入的类别的ID,它将是父类别。

希望有帮助!

相关推荐

Categories manage

我正在尝试向CPT中添加特定类别,只有在添加新帖子时,您才能看到与这些帖子类型相关的类别。此外,我希望能够从后端添加类别,而不是从代码添加类别,因为我有很多类别将要更改。如果有一个插件可以做到这一点,那很好,但我也希望了解它是如何做到的。非常感谢