在 Woocommerce 中以编程方式添加新产品类别

rob*_*b v 5 php database wordpress custom-taxonomy woocommerce

我正在开发一个 Wordpress 网站,并且正在使用 Woocommerce,我有很多产品类别,我想将它们添加到代码中,而不是添加到 Wordpress CMS 本身中。

有谁知道我如何进入可以添加类别的代码。我到处都找过了,即使在数据库中也找不到它。我还想更改代码中的菜单,因为这也会减少很多工作。

任何帮助表示赞赏。

Loi*_*tec 6

Woocommerce 产品类别术语是 WordPress 自定义分类product_cat\xe2\x80\xa6

\n\n
\n

在数据库中,数据位于表wp_termswp_term_taxonomywp_termmeta等下wp_term_relationships

\n
\n\n

1) 要以编程方式添加新的产品类别术语,您将使用专用的 WordPress 功能,wp_insert_term()例如:

\n\n
// Adding the new product category as a child of an existing term (Optional) \n$parent_term = term_exists( \'fruits\', \'product_cat\' ); // array is returned if taxonomy is given\n\n$term_data = wp_insert_term(\n    \'Apple\', // the term \n    \'product_cat\', // the Woocommerce product category taxonomy\n    array( // (optional)\n        \'description\'=> \'This is a red apple.\', // (optional)\n        \'slug\' => \'apple\', // optional\n        \'parent\'=> $parent_term[\'term_id\']  // (Optional) The parent numeric term id\n    )\n);\n
Run Code Online (Sandbox Code Playgroud)\n\n

term Id这将返回一个包含和术语分类 Id 的数组,例如:

\n\n
array(\'term_id\'=>12,\'term_taxonomy_id\'=>34)\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

2)菜单顺序:要设置甚至更改产品类别的菜单顺序,您将使用add_term_meta()Wordpress功能。

\n\n

您将需要产品类别的术语 ID 和唯一的订购数值(2例如此处):

\n\n
add_term_meta( $term_data[\'term_id\'], \'order\', 2 );\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

3) 缩略图:您还可以使用add_term_meta()类似的方法为产品类别设置缩略图 ID (其中最后一个参数是数字缩略图 ID 引用)

\n\n
add_term_meta( $term_data[\'term_id\'], \'thumbnail_id\', 444 );\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n\n

4)在产品中设置产品类别:

\n\n

现在,要将这个新产品类别“Apple”设置为现有产品 ID,您将使用类似的内容(以及从新创建的“Apple”产品类别生成的相应内容$term_id) :

\n\n
wp_set_post_terms( $product_id, array($term_data[\'term_id\']), \'product_cat\', true );\n
Run Code Online (Sandbox Code Playgroud)\n\n

参考:功能wp_set_post_terms()

\n