更改具有重复项目的 WooCommerce 订单的状态

Change status on WooCommerce orders with duplicated items

客户支付了一次,但有时商品在订单中显示两次,这是随机发生的。通常每周两次。

在这种情况下,我需要一个函数来在发生这种情况时更改订单的状态(比如当订单至少有重复的项目名称时)。

这是我的代码尝试:

add_filter( 'woocommerce_cod_process_payment_order_status', 'prefix_filter_wc_complete_order_status', 10, 3 );
add_filter( 'woocommerce_payment_complete_order_status', 'prefix_filter_wc_complete_order_status', 10, 3 );

function prefix_filter_wc_complete_order_status( $status, $order_id, $order ) {
if( ! $order_id ) return;
$order = wc_get_order( $order_id );

$all_products_id = array();
foreach ($order->get_items() as $item_key => $item ){
    $item_name  = $item->get_name();    
    $all_products_id[] = $item_name;
}

$o_num = count($all_products_id);

if($o_num == 1){
    return 'processing';    
}else{
    
    $standard = 0;
    for($i=1;$i<$o_num;$i++){
        if($all_products_id[0] == $all_products_id[i]){
            $standard++;
        }   
    }

    if($standard > 0){
        return 'on-hold';   
    }else{
        return 'processing';
    }   

}

当我测试它时,我得到这个错误:SyntaxError: Unexpected token < in JSON at position 18

如有任何建议,我们将不胜感激。

您的代码中存在一些错误和问题。此外,您不能使用具有相同功能的两个挂钩,因为它们没有相同的参数。

您可以通过这种方式在每个挂钩的分离函数中使用自定义条件函数:

// Custom conditional function
function has_duplicated_items( $order ) {
    $order_items = $order->get_items();
    $items_count = (int) count($order_items);
    
    if ( $items_count === 1 ) {
        return false;
    }
    
    $items_names = array();
    
    // Loop through order items
    foreach( $order_items as $tem_id => $item ){
        $product_id  = $item->get_variation_id() > 0 ? $item->get_variation_id() : $item->get_product_id();
        $items_names[$product_id] = $item->get_name();
    }
    
    return absint(count($items_names)) !== $items_count ? true : false;
}

add_filter( 'woocommerce_cod_process_payment_order_status', 'filter_wc_cod_process_payment_order_status', 10, 2 );
function filter_wc_cod_process_payment_order_status( $status, $order ) {
    return has_duplicated_items( $order ) ? 'on-hold' : 'processing';
}

add_filter( 'woocommerce_payment_complete_order_status', 'filter_wc_payment_complete_order_status', 10, 3 );
function filter_wc_payment_complete_order_status( $status, $order_id, $order ) {
    return has_duplicated_items( $order ) ? 'on-hold' : 'processing';
}

这次应该可以解决错误:"SyntaxError: Unexpected token < in JSON at position 18"

代码进入您的活动子主题(或活动主题)的 function.php 文件。它应该有效。