I would like to display the default product attributes form value and it's regular price in my front end template file.
The var_dump
below shows options in an array. I Need to get the [default_attributes]
values.
<?php
global $product;
echo var_dump( $product );
// Need to get the [default_attributes] values
?>
Get WooCommerce attributes programmatically For attributes, usually the best way is using the $product->get_attribute( $name ) method.
To get all variations ID of a variable product, we can use the below code snippet. $product = wc_get_product($product_id); $variations = $product->get_available_variations(); $variations_id = wp_list_pluck( $variations, 'variation_id' );
To set default attributes manually, first, in the WooCommerce dashboard go to Products and then click on your variable product. Then, select Variable product from the Product data dropdown. After that, under Variations, you have to select the Default Form Values.
In WooCommerce 3+, it's $variation->get_id() from $variation function argument, which is an instance of the WC_Product_Variation . The method get_id() is inherited from WC_Data class. So in your code it should be instead: 'id' => '_text_field_date_expire[' .
To get the default attributes for a variable product you can use WC_Product
method get_default_attributes()
this way:
<?php
global $product;
if( $product->is_type('variable') ){
$default_attributes = $product->get_default_attributes();
// Testing raw output
var_dump($default_attributes);
}
?>
Now to find out which is the corresponding product variation for this "defaults" attributes, is a little more complicated:
<?php
global $product;
if( $product->is_type('variable') ){
$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
}
}
// Now we get the default variation data
if( $is_default_variation ){
// Raw output of available "default" variation details data
echo '<pre>'; print_r($variation_values); echo '</pre>';
// Get the "default" WC_Product_Variation object to use available methods
$default_variation = wc_get_product($variation_id);
// Get The active price
$price = $default_variation->get_price();
}
}
?>
This is tested and works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With