I want to apply new category to product once the order status get "completed" in WooCommerce. Let's say that the Product is in (category A) and I want to apply (category B) on order status "completed".
Is there any way to do this?
I found couple of tutorials but don't know how to combine them:
https://wordpress.org/support/topic/automatically-add-posts-to-a-category-conditionally
How can I achieve this?
Thanks!
Updated
As you want to change the woocommerce category for a product, you should use
wp_set_object_terms()
native WordPress function that accept either the category ID or slug with'product_cat'
taxonomy parameter and NOT'category'
.
The woocommerce_order_status_completed
hook is classically used to fire a callback function when order change to status completed.
This is the code:
add_action('woocommerce_order_status_completed', 'add_category_to_order_items_on_competed_status' 10, 1);
function add_category_to_order_items_on_competed_status( $order_id ) {
// set your category ID or slug
$your_category = 'my-category-slug'; // or $your_category = 123;
$order = wc_get_order( $order_id );
foreach ( $order->get_items() as $item_id => $product_item ) {
$product_id = $product_item->get_product_id();
wp_set_object_terms( $product_id, $your_category, 'product_cat' );
}
}
Or you can use also woocommerce_order_status_changed
hook with a conditional function that will filter order "completed" status:
add_action('woocommerce_order_status_changed', 'add_category_to_order_items_on_competed_status' 10, 1);
function add_category_to_order_items_on_competed_status( $order_id ) {
// set your category ID or slug
$your_category = 'my-category-slug'; // or $your_category = 123;
$order = wc_get_order( $order_id );
if ( $order->has_status( 'completed' ) ) {
foreach ( $order->get_items() as $item_id => $product_item ) {
$product_id = $product_item->get_product_id();
wp_set_object_terms( $product_id, $your_category, 'product_cat' );
}
}
}
This code goes on function.php file of your active child theme or theme.
This code is tested and fully functional.