0

I am create an wordpress plugin for an API. I am getting products, and for each product I get and array of attributes with name and value. I have tried something but it doesn't appear to be doing anything.

foreach($product->attributes as $attribute) {
    $slug = 'pa_' . strtolower($attribute->name);
    $attribute_value = $attribute->value;

    $thedata = [
        $slug => [
            'name'=> $slug, 
            'value'=> $attribute_value,
            'is_visible' => '1',
            'is_variation' => '1',
            'is_taxonomy' => '1'
        ]
    ];

    update_post_meta( $product_id, '_product_attributes', $thedata);
}

My guess is that i have to search ( or add if doesn't exist ) and attribute, then do the same thing for the value. I am not sure.

Facts: - Everything else in the script works, and yes - the $product comes and also the $product_id hold the id of the product that was created a bit above in the script.

John Doe
  • 571
  • 1
  • 9
  • 26

1 Answers1

0

If you only set the value in post_meta, you cant see the attributes on the edit product screen. Try adding wp_set_object_terms to your foreach

foreach($product->attributes as $attribute) {
    $slug = 'pa_' . strtolower($attribute->name);
    $attribute_value = $attribute->value;

    wp_set_object_terms($post_id, attribute->value, $attribute->name, true);  

    $thedata = [
        $slug => [
            'name'=> $slug, 
            'value'=> $attribute_value,
            'is_visible' => '1',
            'is_variation' => '1',
            'is_taxonomy' => '1'
        ]
    ];

    update_post_meta( $product_id, '_product_attributes', $thedata);
}

There is a post about it on SO here.

KGreene
  • 790
  • 7
  • 11
  • Thanks, this adds them on the product page, but I still need them on the attributes page as well, and also the values added, and the connection made. – John Doe Oct 21 '19 at 18:36
  • try making using $thedata[] = and moving update_post_meta outside of the foreach, because it looks like your overwriting '_product_attributes' each loop with the update. – KGreene Oct 21 '19 at 19:14