user3814097 user3814097 - 3 months ago 16
PHP Question

Change product category once the order status get completed

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

https://wordpress.org/support/topic/woocommerce-on-order-complete-insert-quantity-data-into-custom-database-table

How can I achieve this?

Thanks!

Answer

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 );
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $item_id = $item['product_id']
        wp_set_object_terms( $item_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 );
    $order_status =  $order->post->post_status;

    if ( $order->has_status( 'completed' ) ) {
        $items = $order->get_items();
        foreach ( $items as $item ) {
            $item_id = $item['product_id']
            wp_set_object_terms( $item_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.

Comments