WC_API_Orders::get_variation_id()publicWC 1.0

Given a product ID & API provided variations, find the correct variation ID to use for calculation We can't just trust input from the API to pass a variation_id manually, otherwise you could pass the cheapest variation ID but provide other information so we have to look up the variation ID.

Method of the class: WC_API_Orders{}

No Hooks.

Return

Int. Returns an ID if a valid variation was found for this product

Usage

$WC_API_Orders = new WC_API_Orders();
$WC_API_Orders->get_variation_id( $product, $variations );
$product(WC_Product) (required)
Product instance
$variations(array)
-
Default: array()

WC_API_Orders::get_variation_id() code WC 8.6.1

public function get_variation_id( $product, $variations = array() ) {
	$variation_id = null;
	$variations_normalized = array();

	if ( $product->is_type( 'variable' ) && $product->has_child() ) {
		if ( isset( $variations ) && is_array( $variations ) ) {
			// start by normalizing the passed variations
			foreach ( $variations as $key => $value ) {
				$key = str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $key ) ); // from get_attributes in class-wc-api-products.php
				$variations_normalized[ $key ] = strtolower( $value );
			}
			// now search through each product child and see if our passed variations match anything
			foreach ( $product->get_children() as $variation ) {
				$meta = array();
				foreach ( get_post_meta( $variation ) as $key => $value ) {
					$value = $value[0];
					$key = str_replace( 'attribute_', '', wc_attribute_taxonomy_slug( $key ) );
					$meta[ $key ] = strtolower( $value );
				}
				// if the variation array is a part of the $meta array, we found our match
				if ( $this->array_contains( $variations_normalized, $meta ) ) {
					$variation_id = $variation;
					break;
				}
			}
		}
	}

	return $variation_id;
}