How to programmatically set a category for a new Woocommerce creation product?

The solution presented here makes it easy to create "Categories" for a Wordpress post:

//Check if category already exists
$cat_ID = get_cat_ID( $category );

//If it doesn't exist create new category
if($cat_ID == 0) {
        $cat_name = array('cat_name' => $category);
    wp_insert_category($cat_name);
}

//Get ID of category again incase a new one has been created
$new_cat_ID = get_cat_ID($category);

// Create post object
$new_post = array(
    'post_title' => $headline,
    'post_content' => $body,
    'post_excerpt' => $excerpt,
    'post_date' => $date,
    'post_date_gmt' => $date,
    'post_status' => 'publish',
    'post_author' => 1,
    'post_category' => array($new_cat_ID)
);

// Insert the post into the database
wp_insert_post( $new_post );

However, Woocommerce does not recognize these categories. Woocommerce categories are stored elsewhere. How can I programmatically create categories for woocommerce and how to properly assign it to a new message?

+4
source share
2 answers

Woocommerce categories are terms in the product_cat taxonomy. So, to create a category, you can use wp_insert_term:

wp_insert_term(
  'New Category', // the term 
  'product_cat', // the taxonomy
  array(
    'description'=> 'Category description',
    'slug' => 'new-category'
  )
);

This returns term_idand term_taxonomy_id, for example:array('term_id'=>12,'term_taxonomy_id'=>34))

term_id post ( Woocommerce). /, wp_set_object_terms:

wp_set_object_terms( $post_id, $term_id, 'product_cat' );

Btw, woocommerce , , woocommerce, wp cron jobs, , .

+11

:

$product = wc_get_product($id);

:

$product->set_category_ids([ 300, 400 ] );

, , , , set setter, :

$product->save();

. API: https://docs.woocommerce.com/wc-apidocs/class-WC_Product.html

, WC, .

+1

All Articles