以编程方式更新 WooCommerce 产品中设置的自定义属性值 [英] Update programmatically custom attribute value set in a WooCommerce product

查看:23
本文介绍了以编程方式更新 WooCommerce 产品中设置的自定义属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I already have existing product attributes and then use the function below, it removes existing attributes from the product and replaces them with this one attribute.

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

I only want to update this one attribute value with a new value programmatically.

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

Do I have to read the existing attributes array with get_post_meta first and update it? I am just trying to find out if there is an alternative method.

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 如下:

Your "internalSKU" seems to be a custom product attribute. So yes you need first to get the array of product attributes (as your product can have other product attributes set for it), to update only the required value as follows:

// 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 文件中.

Code goes in functions.php file of the active child theme (or active theme).

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

Now you can run this function anywhere defining its $product_id argument (for product id 850) like:

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

经过测试并有效.

这篇关于以编程方式更新 WooCommerce 产品中设置的自定义属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆