WC_Product::get_attribute PHP Method

get_attribute() public method

Returns a single product attribute as a string.
public get_attribute ( string $attribute ) : string
$attribute string to get.
return string
    public function get_attribute($attribute)
    {
        $attributes = $this->get_attributes();
        $attribute = sanitize_title($attribute);
        if (isset($attributes[$attribute])) {
            $attribute_object = $attributes[$attribute];
        } elseif (isset($attributes['pa_' . $attribute])) {
            $attribute_object = $attributes['pa_' . $attribute];
        } else {
            return '';
        }
        return $attribute_object->is_taxonomy() ? implode(', ', wc_get_object_terms($this->get_id(), $attribute_object->get_name(), 'name')) : wc_implode_text_attributes($attribute_object->get_options());
    }

Usage Example

 /**
  * Add woo attributes to a custom field with the same name
  *
  * @param $custom_fields
  * @param $post_id
  *
  * @return mixed
  */
 public function filter_custom_fields($custom_fields, $post_id)
 {
     if (!isset($custom_fields)) {
         $custom_fields = array();
     }
     // Get the product correponding to this post
     $product = new WC_Product($post_id);
     foreach ($product->get_attributes() as $attribute) {
         //$terms = wc_get_product_terms( $product->id, $attribute['name'], array( 'fields' => 'names' ) );
         // Remove the eventual 'pa_' prefix from the attribute name
         $attribute_name = $attribute['name'];
         if (substr($attribute_name, 0, 3) == 'pa_') {
             $attribute_name = substr($attribute_name, 3, strlen($attribute_name));
         }
         $custom_fields[$attribute_name] = explode(',', $product->get_attribute($attribute['name']));
     }
     return $custom_fields;
 }
All Usage Examples Of WC_Product::get_attribute
WC_Product