Automattic\WooCommerce\Internal\StockNotifications\Frontend

SignupService::parse_posted_attributesprivateWC 1.0

Parse variation attributes from source data.

This method extracts attributes that are defined as 'any' in the variation and need to be explicitly specified during signup. These attributes cannot be retrieved directly from the variation since they are not fixed values.

For example, if a t-shirt variation has 'any' size but a specific color, we need to capture the chosen size from the form submission while the color comes from the variation itself.

Method of the class: SignupService{}

No Hooks.

Returns

Array. The posted attributes.

Usage

// private - for code of main (parent) class only
$result = $this->parse_posted_attributes( $source, $variation ): array;
$source(array) (required)
The source data, e.g. $_POST or $_REQUEST.
$variation(WC_Product) (required)
The variation.

Notes

  • See: [WC_Cart::add_to_cart()](/plugin/woocommerce/function/WC_Cart::add_to_cart) for similar attribute parsing logic.

SignupService::parse_posted_attributes() code WC 10.3.6

private function parse_posted_attributes( array $source, \WC_Product $variation ): array {

	if ( ! $variation instanceof \WC_Product_Variation ) {
		return array();
	}

	$product = wc_get_product( $variation->get_parent_id() );
	if ( ! $product ) {
		return array();
	}

	$posted_attributes = array();
	foreach ( $product->get_attributes() as $attribute ) {
		if ( ! $attribute['is_variation'] ) {
			continue;
		}

		$attribute_key = 'attribute_' . sanitize_title( $attribute['name'] );
		if ( isset( $source[ $attribute_key ] ) ) {
			if ( $attribute['is_taxonomy'] ) {
				$value = sanitize_title( wp_unslash( $source[ $attribute_key ] ) );
			} else {
				$value = html_entity_decode( wc_clean( wp_unslash( $source[ $attribute_key ] ) ), ENT_QUOTES, get_bloginfo( 'charset' ) );
			}

			// Don't include if it's empty.
			if ( ! empty( $value ) || '0' === $value ) {
				$posted_attributes[ $attribute_key ] = $value;
			}
		}
	}

	$variation_attributes = $variation->get_variation_attributes();
	// Filter out 'any' variations, which are empty.
	$variation_attributes = array_filter( $variation_attributes );
	$diff                 = array_diff( $posted_attributes, $variation_attributes );

	// Return the posted attributes only if a variation with `any` attribute is detected.
	return ! empty( $diff ) ? $diff : array();
}