Woocommerce update product attributes in php

This php function allows you to update simple product attributes in woocommerce.

<?php


function update_product_attributes($product_id, $attributes){

    $product = new WC_Product($product_id);

    $product_attributes = array();

    delete_transient('wc_attribute_taxonomies');

    foreach ($attributes as $key => $terms) {
        $taxonomy = wc_attribute_taxonomy_name($key); // The taxonomy slug
        $attr_label = ucfirst($key); // attribute label name
        $attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug


        delete_transient('wc_attribute_taxonomies');


        // NEW Attributes: Register and save them
        if (!taxonomy_exists($taxonomy))
            save_product_attribute_from_name($attr_name, $attr_label);

        delete_transient('wc_attribute_taxonomies');

        $is_variation = 0;

        if ($key == "Color") {
            $is_variation = 1;
        }

        $product_attributes[$taxonomy] = array(
            'name' => $taxonomy,
            'value' => '',
            'position' => 0,
            'is_visible' => 1,
            'is_variation' => $is_variation,
            'is_taxonomy' => 1
        );

        foreach ($terms as $value) {
            $term_name = ucfirst($value);
            $term_slug = sanitize_title($value);


            delete_transient('wc_attribute_taxonomies');


            // Check if the Term name exist and if not we create it.
            if (!term_exists($value, $taxonomy))
                wp_insert_term($term_name, $taxonomy, array('slug' => $term_slug)); // Create the term


            delete_transient('wc_attribute_taxonomies');


            // Set attribute values
            wp_set_post_terms($product_id, $term_name, $taxonomy, true);
        }
    }
    update_post_meta($product_id, '_product_attributes', $product_attributes);
    $product->save();
}

Leave a Reply

Your email address will not be published.