Nicetechnology
Nicetechnology

Reputation: 41

WooCommerce how to get a clean label of a product attributes on front end

So, I'm successfully adding products, variations with attributes, etc in a plugin I'm writing. The problem I'm having is that on the frontend the attributes appear as the raw name (e.g. pa_variation_name) rather than a clean looking title (e.g. Variation Name).

I am adding the attribute to the parent product as follows...

$product = wc_get_product($post_id);
$attribute = new WC_Product_Attribute();
$attribute->set_name('pa_variation_name');
$attribute->set_options($attributes_array);
$attribute->set_visible(true);
$attribute->set_variation(true);
$attributes[] = $attribute;

$product->set_attributes($attributes);

$product->save();

And adding the data to the individual variations like this:

update_post_meta($variation_id, 'attribute_pa_variation_name', $args['Description']);

Maybe I'm missing something obvious but how can I set a clean title so I don't have 'pa_whatever' appearing on the frontend?

Upvotes: 1

Views: 755

Answers (1)

Ruvee
Ruvee

Reputation: 9107

"on the frontend the attributes appear as the raw name (e.g. pa_variation_name) rather than a clean looking title (e.g. Variation Name)."

I would use woocommerce wc_attribute_label function. Like this:

wc_attribute_label( $attribute->->get_name() );

For example if I run it on one of my products:

$attributes = $product->get_variation_attributes();

foreach ($attributes as $attribute_name => $attribute_options) 
{
  echo wc_attribute_label($attribute_name);
}

It'll output this:

enter image description here

Note:

  • It's been capitalized.
  • pa_ has been removed.

But if I run my code without wc_attribute_label:

$attributes = $product->get_variation_attributes();

foreach ($attributes as $attribute_name => $attribute_options) 
{
  echo $attribute_name;
}

It'll output this:

enter image description here


For more details you could checkout wc_attribute_label function.

Upvotes: 2

Related Questions