WC_API_Products::save_default_attributes()protectedWC 3.0.0

Save default attributes.

Method of the class: WC_API_Products{}

No Hooks.

Return

WC_Product.

Usage

// protected - for code of main (parent) or child class
$result = $this->save_default_attributes( $product, $request );
$product(WC_Product) (required)
-
$request(WP_REST_Request) (required)
-

Changelog

Since 3.0.0 Introduced.

WC_API_Products::save_default_attributes() code WC 8.6.1

protected function save_default_attributes( $product, $request ) {
	// Update default attributes options setting.
	if ( isset( $request['default_attribute'] ) ) {
		$request['default_attributes'] = $request['default_attribute'];
	}

	if ( isset( $request['default_attributes'] ) && is_array( $request['default_attributes'] ) ) {
		$attributes         = $product->get_attributes();
		$default_attributes = array();

		foreach ( $request['default_attributes'] as $default_attr_key => $default_attr ) {
			if ( ! isset( $default_attr['name'] ) ) {
				continue;
			}

			$taxonomy = sanitize_title( $default_attr['name'] );

			if ( isset( $default_attr['slug'] ) ) {
				$taxonomy = $this->get_attribute_taxonomy_by_slug( $default_attr['slug'] );
			}

			if ( isset( $attributes[ $taxonomy ] ) ) {
				$_attribute = $attributes[ $taxonomy ];

				if ( $_attribute['is_variation'] ) {
					$value = '';

					if ( isset( $default_attr['option'] ) ) {
						if ( $_attribute['is_taxonomy'] ) {
							// Don't use wc_clean as it destroys sanitized characters
							$value = sanitize_title( trim( stripslashes( $default_attr['option'] ) ) );
						} else {
							$value = wc_clean( trim( stripslashes( $default_attr['option'] ) ) );
						}
					}

					if ( $value ) {
						$default_attributes[ $taxonomy ] = $value;
					}
				}
			}
		}

		$product->set_default_attributes( $default_attributes );
	}

	return $product;
}