Looking for help?
< All Topics
Print

Ignore duplicate order items

in some case cause the hosting memory , hosting got trouble about memory when add new order , so , order will duplicate item . to resolve it , you can try use this snippet code. put it to yourtheme/functions.php or any snippet code plugin

add_action('op_add_order_after',function($order,$order_parse_data){
    $item_ids = array();
    $items = isset($order_parse_data['items']) ? $order_parse_data['items'] : array();
    foreach($items as $_item)
    {
        $item_local_id = isset($_item['id']) ? $_item['id'] : 0;
        if($item_local_id)
        {
            $item_ids[] = $item_local_id;
        }
    }
    if(!empty($item_ids))
    {
        global $wpdb;
        $_item_ids = array_map(function($v) {
            return "'" . $v . "'";
        }, $item_ids);
        $sql = $wpdb->prepare( "
            SELECT COUNT(*) c,meta_value,MAX(order_item_id) as max_order_item_id,  GROUP_CONCAT(order_item_id SEPARATOR ',') AS item_ids
            FROM {$wpdb->prefix}woocommerce_order_itemmeta
            WHERE meta_key = '_op_local_id' AND meta_value IN (".implode(',',$_item_ids).") GROUP BY meta_value HAVING c > %d
        ",  1 );
    
        $rows = $wpdb->get_results(  $sql, ARRAY_A);
        foreach($rows as $row)
        {
            $max_item_id = $row['max_order_item_id'];
            $items_ids = explode(',',$row['item_ids']);
            $_items_ids = array_diff($items_ids, array($max_item_id));

            //delete order item
            foreach($_items_ids as $item_id)
            {
                wc_delete_order_item( $item_id );
            }
            // delete order item meta
        }
    }
    
},100,2);
Table of Contents