Wordpress Woocommerce-使用update_post_meta添加产品属性 [英] Wordpress Woocommerce - use update_post_meta to add product attributes
问题描述
我的客户网站中的产品需要某些属性,这些属性是我通过Wordpress管理中的产品->属性添加的.在此导入脚本中,我正在编码,我需要使用功能update_post_meta($post_id, $meta_key, $meta_value)
导入适当的属性和值.
The products in my clients website require certain attributes which I have added via Products -> Attributes in the Wordpress administration. In this import script I'm coding I need to use the function update_post_meta($post_id, $meta_key, $meta_value)
to import the proper attributes and values.
当前,我具有如下功能:
Currently I have the function like so:
update_post_meta( $post_id, '_product_attributes', array());
但是我不确定如何正确传递属性及其值?
However I'm not sure how to properly pass along the attributes and their values?
推荐答案
对,所以花了我一段时间才自己弄清楚,但我最终通过编写以下函数来做到这一点:
Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function:
// @param int $post_id - The id of the post that you are setting the attributes for
// @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go
function wcproduct_set_attributes($post_id, $attributes) {
$i = 0;
// Loop through the attributes array
foreach ($attributes as $name => $value) {
$product_attributes[$i] = array (
'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
'value' => $value, // set attribute value
'position' => 1,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0
);
$i++;
}
// Now update the post with its new attributes
update_post_meta($post_id, '_product_attributes', $product_attributes);
}
// Example on using this function
// The attribute parameter that you pass along must contain all attributes for your product in one go
// so that the wcproduct_set_attributes function can insert them into the correct meta field.
$my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size);
// After inserting post
wcproduct_set_attributes($post_id, $my_product_attributes);
// Woohay done!
我希望此功能对需要在WooCommerce中按语法导入多个属性的其他人有所帮助!
I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!
这篇关于Wordpress Woocommerce-使用update_post_meta添加产品属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!