I have looked at this solution, but it is not completely covering our situation. Auto set Woocommerce product to draft status if order is completed.
I am trying to target specific product variations that have the product attribute taxonomy "pa_type" with a Term name that is "Exclusive purchase". Then if that variation is purchased the parent variable product status must be set to draft.
Update: To handle only a specific product variation with a product attribute taxonomy pa_type
that has the term name "Exclusive purchase
" that will set the parent variable product post status to"draft", use the following:
add_action( 'woocommerce_order_status_changed', 'paid_order_statuses_set_variable_product_to_draft', 10, 4 );
function paid_order_statuses_set_variable_product_to_draft( $order_id, $old_status, $new_status, $order ){
// Only for processing and completed orders
if( ! ( $new_status == 'processing' || $new_status == 'completed' ) )
return; // Exit
// Checking if the action has already been done before
if( get_post_meta( $order_id, '_products_to_draft', true ) )
return; // Exit
$products_set_to_draft = false; // Initializing variable
// Loop through order items
foreach($order->get_items() as $item_id => $item ){
// Get the current WC_Product object instance
$product = $item->get_product();
// Targetting a specific product variations ( Taxonomy: 'pa_type' | term name: 'Exclusive purchase' )
if( $product->is_type('variation') && $product->get_attribute('pa_type') == 'Exclusive purchase' ){
// Get the parent variable product instance object
$parent_product = wc_get_product( $item->get_product_id() );
if ('draft' != $parent_product->get_status() ) {
$product->set_status('draft'); // Set status to draft
$product->save(); // Save the product
$products_set_to_draft = true;
}
}
}
// Mark the action done for this order (to avoid repetitions)
if($products_set_to_draft)
update_post_meta( $order_id, '_products_to_draft', '1' );
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.