以编程方式更新 WooCommerce 产品中设置的自定义属性值

问题描述

如果我已经有现有的产品属性,然后使用下面的函数,它会从产品中删除现有的属性并将它们替换为这一属性

我只想以编程方式用新值更新这个属性值。

我是否必须先使用 get_post_meta 读取现有的属性数组并更新它?我只是想看看是否有替代方法

function update_internalSKU() {
  $product_id = 850;
  $product_attributes = array();
  $product_attributes['internalSKU'] = array(
      'name' => 'internalSKU','value' => 'b8de7569042','position' => 1,'is_visible' => 0,'is_variation' => 0,'is_taxonomy' => 0
  );
  update_post_Meta( $product_id,'_product_attributes',$product_attributes);
}
update_internalSKU();

解决方法

您的 "internalSKU" 似乎是一个自定义产品属性。所以是的,您首先需要获取产品属性数组(因为您的产品可以为其设置其他产品属性),仅更新所需的 value 如下:

// Define the function
function update_internalSKU( $product_id ) {
    // Get product attributes
    $product_attributes = get_post_meta( $product_id,'_product_attributes',true);

    // Loop through product attributes
    foreach( $product_attributes as $attribute => $attribute_data ) {
        // Target specif attribute  by its name
        if( 'internalSKU' === $attribute_data['name'] ) {
            // Set the new value in the array
            $product_attributes[$attribute]['value'] ='b8de7569042'; 
            break; // stop the loop
        }
    }
    // Set updated attributes back in database
    update_post_meta( $product_id,$product_attributes );
}

代码位于活动子主题(或活动主题)的functions.php 文件中。

现在您可以在定义其 $product_id 参数的任何位置运行此函数(对于产品 ID 850,例如:

// Run the function for specific product Id
update_internalSKU( 850 );

经过测试并有效。