Php 在wordpress中将多个属性值添加到产品中
我有逗号分隔的字符串和属性值。 比如说Php 在wordpress中将多个属性值添加到产品中,php,wordpress,woocommerce,attributes,Php,Wordpress,Woocommerce,Attributes,我有逗号分隔的字符串和属性值。 比如说 属性 颜色-红色 类型-防震,时尚,第三值 产品从第三方软件进口。还有属性等 一切都很好,因为只有一个属性值,如颜色-红色。 当有更多属性值时,则在“产品编辑”页面的“属性”部分中,仅显示最后一个值。在本例中为第三个值 我的代码在这里: foreach ($my_product_attributes as $key => $value) { $key = 'pa_' . $key; $commas = substr_count(
- 颜色-红色
- 类型-防震,时尚,第三值
foreach ($my_product_attributes as $key => $value) {
$key = 'pa_' . $key;
$commas = substr_count($value, ",");
if($commas >= 1){
$attribute_values = explode(",", $value);
foreach($attribute_values as $attribute){
wp_set_object_terms($p_id, $attribute, $key, false);
$thedata[sanitize_title($key)] = Array(
'name' => wc_clean($key),
'value' => $attribute,
'postion' => '0',
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
update_post_meta($p_id, '_product_attributes', $thedata);
}
}
我知道我的代码的核心问题,但我不知道在哪里解决它,也不知道如何用foreach覆盖数组中的“value”键,因为您正在对数组使用相同的键 您可以尝试创建属性数组并将其添加到数据数组中
foreach($attribute_values as $attribute){
$attribute_array[] = $attribute;
}
$thedata[sanitize_title($key)] = Array(
'name' => wc_clean($key),
'value' => $attribute_array,
'postion' => '0',
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
您需要更改显示的页面以迭代属性。代码的问题是,您正在为同一个键的每个属性值调用
update\u post\u meta
。这些属性将替换先前为相同关键帧设置的属性。请尝试以下(未测试)代码:
所以,我在这里想得太多了。这是让我工作的代码
foreach ($my_product_attributes as $key => $value) {
$key = 'pa_' . $key;
$attribute_values = explode(",", $value);
wp_set_object_terms($p_id, $attribute_values, $key, false);
$thedata[sanitize_title($key)] = Array(
'name' => wc_clean($key),
'value' => $attribute_values,
'postion' => '0',
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
update_post_meta($p_id, '_product_attributes', $thedata);
}
foreach ($my_product_attributes as $key => $value) {
$key = 'pa_' . $key;
$attribute_values = explode(",", $value);
wp_set_object_terms($p_id, $attribute_values, $key, false);
$thedata[sanitize_title($key)] = Array(
'name' => wc_clean($key),
'value' => $attribute_values,
'postion' => '0',
'is_visible' => '1',
'is_variation' => '0',
'is_taxonomy' => '1'
);
update_post_meta($p_id, '_product_attributes', $thedata);
}