Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programatically set the category for a new Woocommerce Product Creation?

The solution presented here allows me to easily 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 doesn't recognise these categories. Woocommerce categories are stored somewhere else. How can I programmatically create the categories for woocommerce and what is the correct way to assign it to a new post?

like image 929
coderama Avatar asked Nov 01 '14 14:11

coderama


People also ask

How do I manage categories in WooCommerce?

If you log in to your WooCommerce back-end, categories can be managed from Products -› Product Categories. There you can view your existing categories and subcategories on the right and quickly create new category on the left.


1 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 the term_id and term_taxonomy_id, like this: array('term_id'=>12,'term_taxonomy_id'=>34))

Then, associating a new product with the category is simply associating the category term_id with the product post (products are posts in Woocommerce). First, create the product/post and then use wp_set_object_terms:

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

Btw, woocommerce offers functions for these too which might be easier to use but I have experienced issues with woocommerce functions available in wp cron jobs, so these should be enough to get you going.

like image 169
kroky Avatar answered Sep 24 '22 20:09

kroky