First pass at figuring out what the variation ID is based on variation information being passed in via the API.

This commit is contained in:
Justin Shreve 2015-06-08 17:12:24 +00:00
parent eb4b9a7cd1
commit 251636c02e
1 changed files with 55 additions and 2 deletions

View File

@ -897,12 +897,14 @@ class WC_API_Orders extends WC_API_Resource {
}
if ( isset( $item['product_id'] ) ) {
$product = wc_get_product( $item['product_id'] );
$product_id = $item['product_id'];
} elseif ( isset( $item['sku'] ) ) {
$product_id = wc_get_product_id_by_sku( $item['sku'] );
$product = wc_get_product( $product_id );
}
$variation_id = $this->get_variation_id( $product_id, $item );
$product = wc_get_product( $variation_id ? $variation_id : $product_id );
// must be a valid WC_Product
if ( ! is_object( $product ) ) {
throw new WC_API_Exception( 'woocommerce_api_invalid_product', __( 'Product is invalid', 'woocommerce' ), 400 );
@ -973,6 +975,57 @@ class WC_API_Orders extends WC_API_Resource {
}
}
/**
* 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.
* @param int $product_id main product ID
* @return int returns an ID if a valid variation was found for this product
*/
function get_variation_id( $product_id, $item ) {
$variations = array();
$product = wc_get_product( $item['product_id'] );
$variation_id = null;
if ( $product->is_type( 'variable') && $product->has_child() ) {
if ( isset( $item['variations'] ) && is_array( $item['variations'] ) ) {
// start by normalizing the passed variations
foreach ( $item['variations'] as $key => $value ) {
$key = str_replace( 'attribute_', '', str_replace( 'pa_', '', $key ) );
$variations[ $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_', '', str_replace( 'pa_', '', $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, $meta ) ) {
$variation_id = $variation;
break;
}
}
}
}
return $variation_id;
}
/**
* Utility function to see if the meta array contains data from variations
*/
protected function array_contains( $needles, $haystack ) {
foreach ( $needles as $key => $value ) {
if ( $haystack[ $key ] !== $value ) {
return false;
}
}
return true;
}
/**
* Create or update an order shipping method
*