Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...