simlpymarkb
simlpymarkb

Reputation: 385

Update programmatically custom attribute value set in a WooCommerce product

If I already have existing product attributes and then use the function below, it removes existing attributes from the product and replaces them with this one attribute.

I only want to update this one attribute value with a new value programmatically.

Do I have to read the existing attributes array with get_post_meta first and update it? I am just trying to find out if there is an alternative method.

function update_internalSKU() {
  $product_id = 850;
  $product_attributes = array();
  $product_attributes['internalSKU'] = array(
      'name' => 'internalSKU',
      'value' => 'b8de7569042',
      'position' => 1,
      'is_visible' => 0,
      'is_variation' => 0,
      'is_taxonomy' => 0
  );
  update_post_meta( $product_id ,'_product_attributes', $product_attributes);
}
update_internalSKU();

Upvotes: 3

Views: 4249

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254378

Your "internalSKU" seems to be a custom product attribute. So yes you need first to get the array of product attributes (as your product can have other product attributes set for it), to update only the required value as follows:

// Define the function
function update_internalSKU( $product_id ) {
    // Get product attributes
    $product_attributes = get_post_meta( $product_id ,'_product_attributes', true);

    // Loop through product attributes
    foreach( $product_attributes as $attribute => $attribute_data ) {
        // Target specif attribute  by its name
        if( 'internalSKU' === $attribute_data['name'] ) {
            // Set the new value in the array
            $product_attributes[$attribute]['value'] ='b8de7569042'; 
            break; // stop the loop
        }
    }
    // Set updated attributes back in database
    update_post_meta( $product_id ,'_product_attributes', $product_attributes );
}

Code goes in functions.php file of the active child theme (or active theme).

Now you can run this function anywhere defining its $product_id argument (for product id 850) like:

// Run the function for specific product Id
update_internalSKU( 850 );

Tested and works.

Upvotes: 6

Related Questions