在wordpress中向产品添加多个属性值

问题描述 投票:0回答:3

我用逗号分隔字符串和属性值。例如

  1. 属性 红色 类型 - 防震,时尚,第三价值,

产品从第三方软件导入。也是属性等。

一切都很好,因为只有一个属性值,如Color-Red。当有更多属性值时,属性部分中的产品编辑页面仅显示最后一个值。在这种情况下第三个值。

我的代码在这里:

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);
        }
    }

我知道我的代码的核心问题,但我不知道在哪里修复它,以及如何

php wordpress woocommerce attributes
3个回答
1
投票

所以,我在这里过度思考。这是对我有用的代码

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);
}

0
投票

您可能正在使用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'
);

您需要更改显示的页面以迭代属性。


0
投票

你的代码的问题是你在同一个键的每个属性值上调用update_post_meta。这些替换了先前为相同键设置的属性。试试这个(未经测试的)代码:

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)
        {
            //set object term for whatever reason you need.
            wp_set_object_terms($p_id, $attribute, $key, false);
        }                
    }
    else
        $attribute_values = $value;

    $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);
}
© www.soinside.com 2019 - 2024. All rights reserved.