【问题标题】:Update programmatically custom attribute value set in a WooCommerce product以编程方式更新 WooCommerce 产品中设置的自定义属性值
【发布时间】:2021-04-17 18:05:04
【问题描述】:

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

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

我必须先用 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();

【问题讨论】:

    标签: php wordpress woocommerce product taxonomy-terms


    【解决方案1】:

    您的"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', $product_attributes );
    }
    

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

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

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

    经过测试并且有效。

    【讨论】:

    • 谢谢@LoicTheAztec!干杯!!
    猜你喜欢
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-01
    • 2015-06-15
    • 1970-01-01
    • 1970-01-01
    • 2020-11-28
    • 1970-01-01
    相关资源
    最近更新 更多