Skip to content

Instantly share code, notes, and snippets.

@raftaar1191
Created March 10, 2023 13:12
Show Gist options
  • Save raftaar1191/e745c0a0f2f4cb706790fc9b025f6937 to your computer and use it in GitHub Desktop.
Save raftaar1191/e745c0a0f2f4cb706790fc9b025f6937 to your computer and use it in GitHub Desktop.
Find Default Product Variation from WooCommerce
function find_matching_product_variation( $product ) {
$is_default_variation = false;
$default_attributes = $product->get_default_attributes();
foreach($product->get_available_variations() as $variation_values ){
foreach($variation_values['attributes'] as $key => $attribute_value ){
$attribute_name = str_replace( 'attribute_', '', $key );
$default_value = $product->get_variation_default_attribute($attribute_name);
if( $default_value == $attribute_value ){
$is_default_variation = true;
} else {
$is_default_variation = false;
break; // Stop this loop to start next main lopp
}
}
if( $is_default_variation ){
$variation_id = $variation_values['variation_id'];
break; // Stop the main loop
}
}
return $is_default_variation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment