以编程方式更新 WooCommerce 订阅订单行项目

Yal*_*ber 2 php wordpress subscriptions orders woocommerce

我正在尝试允许用户从他们的“我的帐户”面板更新他们订阅的行项目。我可以从订阅 ID 获取他们的订阅并向他们显示更新表。现在,我向他们展示了他们订阅中我通过的产品项目

$subscription = wcs_get_subscription($_GET['subscription']);
$subscription_items = $subscription->get_items();
Run Code Online (Sandbox Code Playgroud)

我想做的是允许用户更新他们产品的数量。因此,如果他们更新数量,我想更新订阅的项目数量,以便使用更新的数量生成未来的订单。我看到WC_Abstract_Order课堂上有 update_product 方法。我认为这可以使用,但我对评论中的注释感到困惑:

* Update a line item for the order.
*
* Note this does not update order totals.
Run Code Online (Sandbox Code Playgroud)

使用它时是否需要重新计算总数?当数量为 0 时,我还需要删除订单项。这可能吗?

因为我没有看到删除项目方法。

谢谢

Yal*_*ber 5

所以我能够通过以下方式完成这项工作。

  1. 从订阅对象中删除所有订单项。
  2. 运行 $_POST 以获取更改的数量
  3. 再次将产品添加到订阅中。

注意:我使用自定义字段 price_level 因为它在订阅期间动态定价,我们希望使用它以便价格与他们订阅时的价格相同。

    //remove product items
    $subscription->remove_order_items('line_item');
    //add product item again
    foreach($_POST['quantity'] as $product_id => $qty) {
        if($qty > 0) {
            //we will need to set dynamic prices based on cusotm field
            $price_level = get_field('coffee_price_level', $subscription->id);
            //Get the product
            $product = wc_get_product($product_id);
            //set the price
            $product->set_price(floatval($price_level));
            $tax = ($product->get_price_including_tax()-$product->get_price_excluding_tax())*$qty;
            //subscription item price level
            $subscription->add_product($product, $qty, array(
                'totals' => array(
                    'subtotal'     => $product->get_price(),
                    'subtotal_tax' => $tax,
                    'total'        => $product->get_price(),
                    'tax'          => $tax,
                    'tax_data'     => array( 'subtotal' => array(1=>$tax), 'total' => array(1=>$tax) )
                )
            ));
        }
    }
Run Code Online (Sandbox Code Playgroud)