Reputation: 11
I've been reading about this functionality that I'd like to implement on my WooCommerce. The idea is that once a product is sold out, a new category "Sold Out" is automatically assigned to it.
Luckily, I've come across this answer code. I added this piece of code:
function action_woocommerce_no_stock( $wc_get_product ) {
$term_ids = array(769);
$tag_ids = array(770);
// Set category ids
$wc_get_product->set_category_ids( $term_ids );
// Product set tag ids
$wc_get_product->set_tag_ids( $tag_ids );
// Save
$wc_get_product->save();
}
add_action( 'woocommerce_no_stock', 'action_woocommerce_no_stock', 10, 1 );
To my functions.php and it works! the problem is that it overwrites all previous categories.
If anyone can guide me how to obtain the previous "product_cat" array and add them with the "Sold Out" category (769) I'd greatly appreciate it.
Upvotes: 1
Views: 1247
Reputation: 29660
You can first use get_category_ids()
OR get_tag_ids()
and then array_merge()
So you get:
// Get product via product ID
$product = wc_get_product( 30 );
// Add this new term IDs
$term_ids = array( 15, 30 );
// Get existing category IDs
$category_ids = $product->get_category_ids();
// Set category IDs
$product->set_category_ids( array_merge( $term_ids, $category_ids ) );
// Save
$product->save();
Note: in your case $wc_get_product
is equal to $product
Upvotes: 2