public function find_matching_product_variation($product, $match_attributes = array())
{
$query_args = array('post_parent' => $product->get_id(), 'post_type' => 'product_variation', 'orderby' => 'menu_order', 'order' => 'ASC', 'fields' => 'ids', 'post_status' => 'publish', 'numberposts' => 1, 'meta_query' => array());
// Allow large queries in case user has many variations or attributes.
$GLOBALS['wpdb']->query('SET SESSION SQL_BIG_SELECTS=1');
foreach ($product->get_attributes() as $attribute) {
if (!$attribute->get_variation()) {
continue;
}
$attribute_field_name = 'attribute_' . sanitize_title($attribute->get_name());
if (!isset($match_attributes[$attribute_field_name])) {
return 0;
}
$value = wc_clean($match_attributes[$attribute_field_name]);
$query_args['meta_query'][] = array('relation' => 'OR', array('key' => $attribute_field_name, 'value' => array('', $value), 'compare' => 'IN'), array('key' => $attribute_field_name, 'compare' => 'NOT EXISTS'));
}
$variations = get_posts($query_args);
if ($variations && !is_wp_error($variations)) {
return current($variations);
} elseif (version_compare(get_post_meta($product->get_id(), '_product_version', true), '2.4.0', '<')) {
/**
* Pre 2.4 handling where 'slugs' were saved instead of the full text attribute.
* Fallback is here because there are cases where data will be 'synced' but the product version will remain the same.
*/
return array_map('sanitize_title', $match_attributes) === $match_attributes ? 0 : $this->find_matching_product_variation($product, array_map('sanitize_title', $match_attributes));
}
return 0;
}