如果在 Woocommerce 中购买了特定变体,则将可变产品设置为草稿

Set a variable product to draft if a specific variation is purchased in Woocommerce

我看过这个解决方案,但它并没有完全涵盖我们的情况。

我正在尝试定位具有产品属性分类法 "pa_type" 且术语名称为 "Exclusive purchase" 的特定产品变体。然后,如果购买了该变体,则必须将父变量产品状态设置为草稿。

感谢任何帮助。

更新: 仅处理具有术语名称 pa_type 的产品属性分类法的特定产品变体 "Exclusive purchase" 将父变量产品 post 状态设置为 "draft",使用以下内容:

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' );
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。已测试并有效。