0

I want to get the Woocommerce variable product variation name. If, for example, I have a product that is available in different sizes: small, medium and large. Then I would like to print for example "large". I have almost got it to work. The problem is, I also get the product name at the same time like: "Product name - Large" Here is my code:

$product_variation = wc_get_product($variation['variation_id']); $product_variation->get_name()

Hope someone can help, thanks. :-)

5 Answers 5

4

i have tested below code it works properly for variation name

$variationId = 39;
$variation = new WC_Product_Variation($variationId);
$variationName = implode(" / ", $variation->get_variation_attributes());
echo $variationName;
1
  • Thank you so much! It works :-)
    – Oscar S.
    Commented Jul 17, 2019 at 16:14
0

Use the get_varation() method. If the attribute is a global attribute it will properly get the name from the taxonomy term for the attribute, and if it's not it will return the value stored with the product.

$product_variation = wc_get_product( $variation['variation_id'] ); 
echo $product_variation->get_attribute( 'size' );
0

I believe this should work fine :

$string = WC_Product_Variation::get_formatted_name();

ref: https://woocommerce.wp-a2z.org/oik_api/wc_product_variationget_formatted_name/

-1

use this here you get variation name

$productId = 1; //product id here
$handle = new WC_Product_Variable($productId);
$variationData = $handle->get_children();
foreach ($variationData as $value) {
$variation_id = $value;
$single_variation = new WC_Product_Variation($value);
$var_slug = $single_variation->slug;
echo "<br/>".$name = implode(" / ", $single_variation->get_variation_attributes());//here you get product name
}
-2

Please try below code. it will output a variation name of attribute size by variation id.

$variation = wc_get_product($variation['variation_id']);
$variation_attributes = $variation->get_variation_attributes();
$variation_name = ucfirst($variation_attributes['attribute_pa_size']);
echo $variation_name;

let me know if this works for you.

2
  • This will only work if the attribute is global, and will only return the slug. ucfirst() is a hack to make the slug look like the attribute name, and will not work properly if the value is more than one word, or if the label is not the same as the slug. Commented Jul 16, 2019 at 11:03
  • Thank you @jacob for your explanation. Commented Jul 16, 2019 at 11:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.