繁体   English   中英

如何将类别设置为产品woocommerce

[英]How to set category to product woocommerce

是否可以向woocommerce帖子添加类别?

我正在创建我的产品如下:

// creates woocommerce product 
$product = array(
    'post_title'    => $name,
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => $current_user->ID,
    'post_type'     =>'product'
);

// Insert the post into the database
$product_ID = wp_insert_post($product);

我有一个名为“树”的类别,我必须将上述产品添加到其中。 我尝试了以下但没有成功。 是否有一些特殊的方法来添加类别?

wp_set_object_terms($productID, array('Tree'), 'product_cat');

经过一些试验和错误,我通过以下方式解决了它:

// Creates woocommerce product 
$product = array(
    'post_title'    => $name,
    'post_content'  => '',
    'post_status'   => 'publish',
    'post_author'   => $current_user->ID,
    'post_type'     =>'product'
);

// Insert the post into the database
$product_ID = wp_insert_post($product);

// Gets term object from Tree in the database. 
$term = get_term_by('name', 'Tree', 'product_cat');

wp_set_object_terms($product_ID, $term->term_id, 'product_cat');

更多信息参考:

如果您需要多个类别,只需传递一个数组:

$categories = [ 'Some Category', 'Some other Category' ];

// Overwrite any existing term
wp_set_object_terms( $product_id, $categories, 'product_cat' );


// Or, set last argument to true to append to existing terms
wp_set_object_terms( $product_id, $categories, 'product_cat', true );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM