且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-03 12:34:40

您的 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 );

经过测试并有效.