如果在Woocommerce中购买了特定的变体,则设置可变产品以起草

时间:2018-10-29 11:23:24

标签: php wordpress woocommerce custom-taxonomy variations

我已经看过这个解决方案,但是它不能完全涵盖我们的情况。 Auto set Woocommerce product to draft status if order is completed

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

更新:仅处理名称为pa_type的产品属性分类为 Exclusive purchase 的特定产品变体“ ,它将父变量产品发布状态设置为“草稿”,请使用以下命令:

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文件中。经过测试,可以正常工作。