首页 > 解决方案 > 在 Woocommerce 中以编程方式添加新产品类别

问题描述

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

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

任何帮助表示赞赏。

标签: phpdatabasewordpresswoocommercecustom-taxonomy

解决方案


Woocommerce 产品类别术语是 WordPress 自定义分类法product_cat……

在数据库中,数据也位于表wp_termswp_term_taxonomy和 下面。wp_termmetawp_term_relationships

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 分类 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()


推荐阅读