【问题标题】:How to set category to product woocommerce如何将类别设置为产品 woocommerce
【发布时间】:2014-11-30 23:38:04
【问题描述】:

是否可以在 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');

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    经过反复试验,我通过以下方式解决了它:

    // 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');
    

    更多信息参考:

    【讨论】:

    • 如果你在不同的模式下得到 $termID,并且它是一个字符串,WP 会创建一个新的带有数字名称的术语,所以在第二个参数之前添加 (int)wp_set_object_terms($product_ID, (int)$term_id, 'product_cat');
    【解决方案2】:

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

    $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 );
    

    【讨论】:

    • 请注意,这将覆盖所有当前分配的类别。
    • 您可以将 true 作为第四个参数传递以将您的类别附加到现有类别。 wp_set_object_terms($product_id, $categories, 'product_cat', true);
    • 感谢 Zade 和 Matthew Ediger。我已经用这些笔记更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2021-02-08
    • 2021-05-08
    • 2021-08-05
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多