sim*_*rkb 3 php wordpress product woocommerce taxonomy-terms
如果我已经拥有现有的产品属性,然后使用下面的函数,它会从产品中删除现有的属性,并将其替换为这一属性。
我只想以编程方式用新值更新这个属性值。
我是否必须先使用 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();
Run Code Online (Sandbox Code Playgroud)
您的"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 );
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的functions.php 文件中。
$product_id
现在您可以在任何定义其参数(对于产品 id 850
)的地方运行此函数,例如:
// Run the function for specific product Id
update_internalSKU( 850 );
Run Code Online (Sandbox Code Playgroud)
经过测试并有效。