【问题标题】:Save custom cart item data from dynamic created cart on order creation in Woocommerce在 Woocommerce 中创建订单时从动态创建的购物车中保存自定义购物车项目数据
【发布时间】:2019-05-20 01:29:08
【问题描述】:

重要提示:我没有将 functions.php 用于任何购物车功能。我正在使用独立的 php 文件,它必须保持这种状态。

在 Woocommerce 中,我正在创建一个购物车,使用以下方法动态添加产品:

global $woocommerce;
$cart = $woocommerce->cart;

//set the custom item data
$item_data = array();

 $product_id = '121';

 $item_data = array(
 'plain_data' => 'test data',
 'array_data' => array('URL' => 'URL',  'Signals' => 'SIGNALS')
  );

//Add it to the cart
$cart->add_to_cart($product_id, 1, null, null, $item_data);

然后我使用以下命令从购物车创建订单:

global $woocommerce;
$cart = $woocommerce->cart;

$order_data = array('payment_method' => 'PayPal');

$checkout = $woocommerce->checkout();
$order_id = $checkout->create_order($order_data);

但我添加的自定义商品数据没有保存在订单中。

我做错了什么?

【问题讨论】:

    标签: php wordpress woocommerce cart orders


    【解决方案1】:

    由于您不想使用任何挂钩,因此您必须在创建订单后设置自定义购物车商品数据……所以请尝试以下操作:

    尝试以下方法:

    $product_id = '121';
    
    $item_data = array(
        'plain_data' => 'test data',
        'array_data' => array('URL' => 'URL',  'Signals' => 'SIGNALS')
    );
    
    $item_data_keys = array_keys($item_data); // Get array keys
    
    
    //Add it to the cart
    WC()->cart->add_to_cart($product_id, 1, 0, array(), $item_data);
    
    // Create order
    $order_id = WC()->checkout->create_order( array('payment_method' => 'PayPal') );
    
    // Get an instance of the WC_Order Object
    $order = wc_get_order($order_id);
    
    // Loop through order items
    foreach( $order->get_items() as $item ){
        // Loop though custom item data
        foreach( $item_data_keys as $item_data_key ){
            // set custom item data
            $item->update_meta_data( $item_data_key, $item_data[$item_data_key] );
        }
        // Save item data
        $item->save();
    }
    // Save order
    $order->save();
    

    经过测试并且有效。

    注意:global woocommerce 现在已被 WC() 替换了一段时间。

    【讨论】:

    • 很好的答案,谢谢!但是,如果每个购物车商品都有唯一的数据呢?这不会将相同的数组应用于每个订单项吗?再次感谢!
    • 我想通了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-04-16
    • 2020-10-19
    • 2015-12-10
    • 2019-09-18
    • 2017-08-25
    • 1970-01-01
    • 2023-03-30
    相关资源
    最近更新 更多