0

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

1 Answer 1

4

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);
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.