How to set woocommerce product attribute programmatically?

by filiberto , in category: PHP CMS , 5 months ago

How to set woocommerce product attribute programmatically?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by mac , 5 months ago

@filiberto 

To set a WooCommerce product attribute programmatically, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Set the product attribute name
$attribute_name = 'color';

// Check if the attribute already exists
$attribute = wc_get_attribute($attribute_name);

if(!$attribute){
    // Define the attribute arguments
    $args = array(
        'name' => $attribute_name,
        'label' => ucwords($attribute_name),
        'type' => 'select',
        'default' => '',
        'position' => 0,
        'is_visible' => true,
        'is_variation' => true,
        'is_taxonomy' => false,
    );

    // Add the attribute
    $attribute_id = wc_create_attribute($args);
    
    // Set the attribute values
    $attribute_values = array('Red', 'Blue', 'Green');
    update_attribute_values($attribute_id, $attribute_values);
}

// Function to update attribute values
function update_attribute_values($attribute_id, $values){
    $attribute = wc_get_attribute($attribute_id);
    
    foreach($values as $value){
        // Check if the value already exists
        $term = get_term_by('name', $value, $attribute->slug);
        if(!$term){
            // Add the attribute value
            $term_args = array(
                'name' => $value,
                'slug' => $value,
                'term_group' => 0,
            );
            wp_insert_term($value, $attribute->slug, $term_args);
        }
    }
}


This code snippet first checks if the attribute already exists and if not, creates it. It then sets the attribute values for the specified attribute. You can modify the attribute name, label, type, and values to suit your requirements.