Skip to content

Instantly share code, notes, and snippets.

@ashokdhaduk
Forked from tanmay27vats/function.php
Created May 28, 2018 04:44
Show Gist options
  • Save ashokdhaduk/d26a052ac13c34345e4cc9f5167e7aa2 to your computer and use it in GitHub Desktop.
Save ashokdhaduk/d26a052ac13c34345e4cc9f5167e7aa2 to your computer and use it in GitHub Desktop.
Get product's default variation ID, variation price or variation object without plugin.
function tv_find_matching_product_variation( $product, $attributes )
{
foreach( $attributes as $key => $value )
{
if( strpos( $key, 'attribute_' ) === 0 )
{
continue;
}
unset( $attributes[ $key ] );
$attributes[ sprintf( 'attribute_%s', $key ) ] = $value;
}
if( class_exists('WC_Data_Store') )
{
$data_store = WC_Data_Store::load( 'product' );
return $data_store->find_matching_product_variation( $product, $attributes );
}
else
{
return $product->get_matching_variation( $attributes );
}
}
//on product single page.
/* $attributes something like this. */
/*$attributes = array(
'pa_size' => 'small',
'pa_color' => 'red',
'pa_brand' => 'nike'
);*/
$variation_id = milkbed_find_matching_product_variation($product, $product->default_attributes);
$variable_product = wc_get_product($variation_id);
//$default_variation_regular_price = $variable_product->regular_price;
//$default_variation_sale_price = $variable_product->sale_price;
$default_variation_price = $variable_product->price;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment