Maha Dev
Maha Dev

Reputation: 3965

Woocommerce create variable product multiple attributes programmatically

I am creating woocommerce variable product programmatically. Successfully created single attribute(size) but now i am trying to create another attribute (color). I have this attributes array from my form.

Array
(
    [0] => size
    [1] => color
)

and here is the code i tried :

       $args_t = array(
                'orderby' => 'name',
                'order' => 'ASC',
                'hide_empty' => true,
                'fields' => 'names'
            );

        if ($product_attributes) {
            foreach ($product_attributes as $attr) {
                $avail_attributes = array();
                $avail_attributes = get_terms(wc_attribute_taxonomy_name($attr), $args_t);
                $attr = 'pa_'.$attr;
                wp_set_object_terms($new_product_id, $avail_attributes, $attr);
                $thedata = array();
                $thedata = Array($attr => Array(
                        'name' => $attr,
                        'value' => '',
                        'postion' => '0',
                        'is_visible' => '1',
                        'is_variation' => '1',
                        'is_taxonomy' => '1'
                ));
                update_post_meta($new_product_id, '_product_attributes', $thedata);
            }
        }

Here is the screenshot of current situation:

enter image description here

Upvotes: 0

Views: 3725

Answers (1)

Reigel Gallarde
Reigel Gallarde

Reputation: 65264

there are problems in your code.. the obvious one is that you are updating the post meta inside the foreach loop. Making it overwriting the current value until the last one. Please try the code below.

    if ($product_attributes) {
        $thedata = array();
        foreach ($product_attributes as $attr) {
            $avail_attributes = array();
            $avail_attributes = get_terms(wc_attribute_taxonomy_name($attr), $args_t);
            $attr = 'pa_'.$attr;
            wp_set_object_terms($new_product_id, $avail_attributes, $attr);
            $thedata[sanitize_title($attr)] = Array(
                    'name' => wc_clean($attr),
                    'value' => '',
                    'postion' => '0',
                    'is_visible' => '1',
                    'is_variation' => '1',
                    'is_taxonomy' => '1'
            );
        }
        update_post_meta($new_product_id, '_product_attributes', $thedata);
    }

Upvotes: 4

Related Questions