WC_Product_Data_Store_CPT::update_attributes()protectedWC 3.0.0

Update attributes which are a mix of terms and meta data.

Method of the class: WC_Product_Data_Store_CPT{}

No Hooks.

Return

null. Nothing (null).

Usage

// protected - for code of main (parent) or child class
$result = $this->update_attributes( $product, $force );
$product(WC_Product) (required) (passed by reference — &)
Product object.
$force(true|false)
Force update. Used during create.
Default: false

Changelog

Since 3.0.0 Introduced.

WC_Product_Data_Store_CPT::update_attributes() code WC 9.4.2

protected function update_attributes( &$product, $force = false ) {
	$changes = $product->get_changes();

	if ( $force || array_key_exists( 'attributes', $changes ) ) {
		$attributes  = $product->get_attributes();
		$meta_values = array();

		if ( $attributes ) {
			foreach ( $attributes as $attribute_key => $attribute ) {
				$value = '';

				if ( is_null( $attribute ) ) {
					if ( taxonomy_exists( $attribute_key ) ) {
						// Handle attributes that have been unset.
						wp_set_object_terms( $product->get_id(), array(), $attribute_key );
					} elseif ( taxonomy_exists( urldecode( $attribute_key ) ) ) {
						// Handle attributes that have been unset.
						wp_set_object_terms( $product->get_id(), array(), urldecode( $attribute_key ) );
					}
					continue;

				} elseif ( $attribute->is_taxonomy() ) {
					wp_set_object_terms( $product->get_id(), wp_list_pluck( (array) $attribute->get_terms(), 'term_id' ), $attribute->get_name() );
				} else {
					$value = wc_implode_text_attributes( $attribute->get_options() );
				}

				// Store in format WC uses in meta.
				$meta_values[ $attribute_key ] = array(
					'name'         => $attribute->get_name(),
					'value'        => $value,
					'position'     => $attribute->get_position(),
					'is_visible'   => $attribute->get_visible() ? 1 : 0,
					'is_variation' => $attribute->get_variation() ? 1 : 0,
					'is_taxonomy'  => $attribute->is_taxonomy() ? 1 : 0,
				);
			}
		}
		// Note, we use wp_slash to add extra level of escaping. See https://codex.wordpress.org/Function_Reference/update_post_meta#Workaround.
		$this->update_or_delete_post_meta( $product, '_product_attributes', wp_slash( $meta_values ) );
	}
}