我在 Wordpress 网站上工作,我正在使用 Woocommerce,我有很多产品类别,我想将它们添加到代码中,而不是在 Wordpress CMS 本身中。
有谁知道我如何进入可以添加类别的代码。我到处都看过,甚至在数据库中也找不到它。而且我还想在代码中更改我的菜单,因为那样也会减少很多工作。
感谢任何帮助。
最佳答案
Woocommerce 产品类别术语是 WordPress 自定义分类法 product_cat
...
In the database the data is located under the tables
wp_terms
,wp_term_taxonomy
,wp_termmeta
andwp_term_relationships
too.
1) 要以编程方式添加新产品类别术语,您将使用专用的 WordPress 功能 wp_insert_term()
喜欢:
// Adding the new product category as a child of an existing term (Optional)
$parent_term = term_exists( 'fruits', 'product_cat' ); // array is returned if taxonomy is given
$term_data = wp_insert_term(
'Apple', // the term
'product_cat', // the Woocommerce product category taxonomy
array( // (optional)
'description'=> 'This is a red apple.', // (optional)
'slug' => 'apple', // optional
'parent'=> $parent_term['term_id'] // (Optional) The parent numeric term id
)
);
这将返回包含term Id
和Term taxonomy Id 的数组,例如:
array('term_id'=>12,'term_taxonomy_id'=>34)
2) 菜单顺序:要设置甚至更改产品类别的菜单顺序,您将使用 add_term_meta()
WordPress 功能。
您将需要产品类别的术语 ID 和唯一的订购数值(例如,此处为 2
):
add_term_meta( $term_data['term_id'], 'order', 2 );
3) 缩略图:您还将使用 add_term_meta()
使用类似(其中最后一个参数是数字缩略图 ID 引用) 将缩略图 ID 设置为产品类别:
add_term_meta( $term_data['term_id'], 'thumbnail_id', 444 );
4)在产品中设置产品类别:
现在要将这个新产品类别“Apple”设置为现有产品 ID,您将使用类似的东西(以及从新创建的相应生成的 $term_id
“Apple”产品类别):
wp_set_post_terms( $product_id, array($term_data['term_id']), 'product_cat', true );
供引用:函数wp_set_post_terms()
关于php - 在 Woocommerce 中以编程方式添加新产品类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53460487/