【问题标题】:Update WooCommerce product price and stock更新 WooCommerce 产品价格和库存
【发布时间】:2020-10-29 21:37:19
【问题描述】:

我有外部 REST API,我正在从中构建一个这样的数组:

$arr = array(
1 => array('code' => '0100686', 'qty' => '2', 'price' => '65.22'),
2 => array('code' => '0100687', 'qty' => '1', 'price' => '5.23'),
3 => array('code' => '0100688', 'qty' => '8', 'price' => '0.28')
);

在此之后,我需要更新 WooCommerce 中产品的价格和数量。 (上面的数组代码是WC中的SKU)。

之后我的代码如下:

foreach ($arr as $single) {
$product_id = wc_get_product_id_by_sku($single['code']);

// I need here to update the product price
// I need here to update the product in stock

}

我搜索了很多解决方案,直接通过 SQL Query 或带有一些钩子,他们说我应该进行临时清理等......我无法想出一个最好的解决方案。您能帮我完成这项任务的最佳解决方案吗?

【问题讨论】:

    标签: php wordpress woocommerce wordpress-rest-api


    【解决方案1】:

    你可以试试这个方法:

    $arr = array(
        array( 'code' => '0100686', 'qty' => '2', 'price' => '65.22' ),
        array( 'code' => '0100687', 'qty' => '1', 'price' => '5.23' ),
        array( 'code' => '0100688', 'qty' => '8', 'price' => '0.28' )
    );
    foreach ( $arr as $single ) {
        $product_id = wc_get_product_id_by_sku( $single['code'] );
        if ( ! $product_id ) {
            continue;
        }
        $product = new WC_Product( $product_id );
        if ( ! $product ) {
            continue;
        }
        $product->set_price( $single['price'] );
        $product->set_stock_quantity( $single['qty'] );
        $product->save();
    }
    

    【讨论】:

      【解决方案2】:

      正如你所说,有很多方法。在你的循环中,你可能会使用WC_Product::setPrice() 方法。作为explained here,你可以像这样使用它:

      foreach ($arr as $single) {
          $product_id = wc_get_product_id_by_sku($single['code']);
          $wcProduct = new WC_Product($product_id);
      
          //price in cents
          $wcProduct->set_price(300);
          $wcProduct->save();
         }
      

      【讨论】:

        猜你喜欢
        • 2021-08-01
        • 1970-01-01
        • 2021-03-16
        • 1970-01-01
        • 2021-11-08
        • 2018-10-13
        • 2017-05-12
        • 2018-04-26
        • 2018-01-31
        相关资源
        最近更新 更多