php - Change product category once the order status get completed -
i want apply new category product once order status "completed" in woocommerce. let's product in (category a) , want apply (category b) on order status "completed".
is there way this?
i found couple of tutorials don't know how combine them:
https://wordpress.org/support/topic/automatically-add-posts-to-a-category-conditionally
how can achieve this?
thanks!
updated (compatibility woocommerce 3+)
as want change woocommerce category product, should use
wp_set_object_terms()
native wordpress function accept either category id or slug with'product_cat'
taxonomy parameter , not'category'
.
the woocommerce_order_status_completed
hook classically used fire callback function when order change status completed.
this 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 category id or slug $your_category = 'my-category-slug'; // or $your_category = 123; $order = wc_get_order( $order_id ); foreach ( $order->get_items() $item_id => $product_item ) { // compatibility wc +3 if ( version_compare( wc_version, '3.0', '<' ) ) $product_id = $product_item['product_id']; else $product_id = $product_item->get_product_id(); wp_set_object_terms( $product_id, $your_category, 'product_cat' ); } }
or can use woocommerce_order_status_changed
hook conditional function 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 category id or slug $your_category = 'my-category-slug'; // or $your_category = 123; $order = wc_get_order( $order_id ); $order_status = $order->post->post_status; if ( $order->has_status( 'completed' ) ) { foreach ( $order->get_items() $item_id => $product_item ) { // compatibility wc +3 if ( version_compare( wc_version, '3.0', '<' ) ) $product_id = $product_item['product_id']; else $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 active child theme or theme.
this code tested , functional.
Comments
Post a Comment