1

As caption, I would like get the product attributes as attribute code like 'Label_x' for example 'Label_Hot', 'Label_Big_Sale' can't create Attributes object with all attribute

I try the code as following:

public function label ($product)
{
$attributes = $product->getAttribute();
 foreach ($attributes as $attribute) { 
 if (stristr($attribute, 'label')==true) 
 {
 ...........logic..........
 }
 }
}
Amit Bera
77.8k21 gold badges127 silver badges240 bronze badges
asked Jan 26, 2016 at 7:00

2 Answers 2

2

Change $product->getAttribute() to $product->getAttributes():

/**
 * Retrieve product attributes
 * if $groupId is null - retrieve all product attributes
 *
 * @param int $groupId Retrieve attributes of the specified group
 * @param bool $skipSuper Not used
 * @return \Magento\Eav\Model\Entity\Attribute\AbstractAttribute[]
 * @SuppressWarnings(PHPMD.UnusedFormalParameter)
 */
public function getAttributes($groupId = null, $skipSuper = false)
{
 $productAttributes = $this->getTypeInstance()->getEditableAttributes($this);
 if ($groupId) {
 $attributes = [];
 foreach ($productAttributes as $attribute) {
 if ($attribute->isInGroup($this->getAttributeSetId(), $groupId)) {
 $attributes[] = $attribute;
 }
 }
 } else {
 $attributes = $productAttributes;
 }
 return $attributes;
}

Now you would be able to loop through the attributes and have access to the attribute object. You are able to use $attribute->getCode() to get the code.

answered Jan 26, 2016 at 11:09
1
  • I want to list only custom attributes of a product in Magento 2, how can I achieve it ?? Commented Apr 26, 2016 at 7:41
2

Custom product attributes with their values:

$custom = []; 
$attributes = $product->getCustomAttributes(); 
foreach ($attributes as $attribute) { 
 $custom[$attribute->getAttributeCode()] = [$attribute->getValue()]; 
}
answered Sep 16, 2016 at 15:41

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.