Woocommerce Product category terms are a WordPress custom taxonomy product_cat
…
In the database the data is located under the tables wp_terms
, wp_term_taxonomy
, wp_termmeta
and wp_term_relationships
too.
1) To add a new product category term programmatically you will use the dedicated WordPress function wp_insert_term()
like:
// 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
)
);
This will return the an array containing the term Id
and the Term taxonomy Id like :
array('term_id'=>12,'term_taxonomy_id'=>34)
2) Menu Order: To set or even change the menu order of your product categories, you will use add_term_meta()
Wordpress function.
You will need the term Id of your product category and the unique ordering numeric value (Here 2
for example):
add_term_meta( $term_data['term_id'], 'order', 2 );
3) Thumbnail: You will also use add_term_meta()
to set a thumbnail ID to a product category using something like (where the last argument is the numeric thumbnail ID reference):
add_term_meta( $term_data['term_id'], 'thumbnail_id', 444 );
4) Set a product category in a product:
Now to set this new product category "Apple" to an existing product ID you will use something like (with the corresponding generated $term_id
from new created "Apple" product category):
wp_set_post_terms( $product_id, array($term_data['term_id']), 'product_cat', true );
For reference: Function wp_set_post_terms()