【问题标题】:Add a product programmatically to WooCommerce subscription changing its name & price以编程方式将产品添加到 WooCommerce 订阅更改其名称和价格
【发布时间】:2021-05-09 16:37:47
【问题描述】:

我正在尝试以编程方式将现有产品添加到订单中,但仅针对该订单更改名称和价格。

我可以使用以下方法轻松添加现有产品:

$subscription->add_product( get_product( '969' ), 1);

如何设置自定义名称和价格?

如果我可以设置,那么我知道我可以运行以下命令来重新计算总数:

$subscription->calculate_totals();

【问题讨论】:

    标签: php methods woocommerce product woocommerce-subscriptions


    【解决方案1】:

    要更改添加到订阅的产品价格和名称,请尝试以下操作:

    $product   = wc_get_product('969');
    $quantity  = 1;
    $new_price = 100; // (Excluding taxes).
    $new_name  = 'New name';
    
    // Add the product
    $item_id  = $subscription->add_product( $product, $quantity );
    
    // Get the instance of WC_Order_Item_Product Object from item Id
    $item = $subscription->get_item( $item_id, false ); // Get the 
    
    // Change name and price
    $item->set_name( $new_name ); // set new name
    $item->set_subtotal( $new_price * $item_quantity ); // set new price
    
    // Calculate item taxes
    $item->calculate_taxes( array(
        'country'  => $subscription->get_billing_country() ? $subscription->get_billing_country() : $subscription->get_shipping_country(),
        'state'    => $subscription->get_billing_state() ? $subscription->get_billing_state() : $subscription->get_shipping_state(),
        'postcode' => $subscription->get_billing_postcode() ? $subscription->get_billing_postcode() : $subscription->get_shipping_postcode(),
        'city'     => $subscription->get_billing_city() ? $subscription->get_billing_city() : $subscription->get_shipping_city(),
    ) );
    
    $item->save(); // Save item
    
    $subscription->calculate_totals(); // Refresh subscription totals and save.
    

    它应该可以工作。

    相关:Programmatically created WooCommerce order have no tax for new users

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-03
      • 2017-03-11
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2020-05-20
      • 2018-06-17
      • 1970-01-01
      相关资源
      最近更新 更多