Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
4.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...