【问题标题】:WooCommerce Recover Cart from Session DataWooCommerce 从会话数据中恢复购物车
【发布时间】:2016-10-26 07:09:35
【问题描述】:

我正在为一个小型放弃购物车恢复插件工作,我需要从woocommerce_sessions 表中恢复购物车。

这是购物车中 1 个可变产品的未序列化购物车数据。

array (size=1)
  'cart' => 
    array (size=9)
      'product_id' => int 22
      'variation_id' => int 24
      'variation' => 
        array (size=1)
          'attribute_pa_color' => string 'green' (length=5)
      'quantity' => int 1
      'line_total' => float 20
      'line_tax' => int 0
      'line_subtotal' => int 20
      'line_subtotal_tax' => int 0
      'line_tax_data' => 
        array (size=2)
          'total' => 
            array (size=0)
              empty
          'subtotal' => 
            array (size=0)
              empty

我正在尝试使用这些数据恢复整个购物车。我知道可以遍历这个数组并通过

将商品添加到购物车
WC_Cart::add_to_cart( $product_id, $quantity, $variation_id, $variation );

但是,由于数据存储在woocommerce_sessions 表中并且完全兼容 WooCommerce,因此有没有更优雅的方法呢?

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    我没有找到任何其他解决方案,所以只是先清除购物车,然后通过购物车数据循环并以编程方式将商品添加到购物车。这是代码的样子。

    if ( $cart_data ) {
        WC()->cart->empty_cart();
    
        foreach ( $cart_data as $product ) {
    
            // Validate Product data
            $product_id   = isset( $product['product_id'] )    ? (int) $product['product_id']   : 0;
            $quantity     = isset( $product['quantity'] )      ? (int) $product['quantity']     : 1;
            $variation_id = isset( $product['variation_id'] )  ? (int) $product['variation_id'] : 0;
            $variation    = isset( $product['variation'] )     ? $product['variation']          : array();
    
            WC()->cart->add_to_cart( $product_id, $quantity, $variation_id, $variation );
        }
        WC()->cart->calculate_totals();
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 2021-12-01
      • 1970-01-01
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多