Daniel Daniel - 2 months ago 117
PHP Question

Wordpress Woocommerce - use update_post_meta to add product attributes

The products in my clients website require certain attributes which I have added via Products -> Attributes in the Wordpress administration. In this import script I'm coding I need to use the function

update_post_meta($post_id, $meta_key, $meta_value)
to import the proper attributes and values.

Currently I have the function like so:

update_post_meta( $post_id, '_product_attributes', array());


However I'm not sure how to properly pass along the attributes and their values?

Answer

Right so it took me a while to figure it out myself but I finally managed to do this by writing the following function:

// @param int $post_id - The id of the post that you are setting the attributes for
// @param array[] $attributes - This needs to be an array containing ALL your attributes so it can insert them in one go
function wcproduct_set_attributes($post_id, $attributes) {
    $i = 0;
    // Loop through the attributes array
    foreach ($attributes as $name => $value) {
        $product_attributes[$i] = array (
            'name' => htmlspecialchars( stripslashes( $name ) ), // set attribute name
            'value' => $value, // set attribute value
            'position' => 1,
            'is_visible' => 1,
            'is_variation' => 1,
            'is_taxonomy' => 0
        );

        $i++;
    }

    // Now update the post with its new attributes
    update_post_meta($post_id, '_product_attributes', $product_attributes);
}

// Example on using this function
// The attribute parameter that you pass along must contain all attributes for your product in one go
// so that the wcproduct_set_attributes function can insert them into the correct meta field.
$my_product_attributes = array('hdd_size' => $product->hdd_size, 'ram_size' => $product->ram_size);

// After inserting post
wcproduct_set_attributes($post_id, $my_product_attributes);

// Woohay done!

I hope this function will help other people if they need to import multiple attributes pro-grammatically in WooCommerce!