2

I have a custom attribute which has 15 text values. I am using $_product->getResource()->getAttribute($attributecode)->getFrontend()->getValue($_product); . In catalog page I have used above code get the text value of attribute for every product in for loop, is it impacted on performance ? Above code everytime call in database to get the attribute optiontext ?

2 Answers 2

0

In your product/list.phtml you should have access to the custom attribute through a simple

<?php echo $_product->getCustomAttributeCode() ?>

Remember to set your custom attribute "Used in Product Listing"

3
  • thank you for answer, but I am not asking for how to get customattribute from product object, please update your answer Commented Dec 22, 2022 at 16:18
  • Hi Niraj, maybe I didn't understand the question, but taking the attribute directly from the object passed by the collection I would say you solve any doubts about the performance.
    – Alex
    Commented Dec 22, 2022 at 16:29
  • my question is if we use $_product->getCustomAttributeCode() code in for loop and for loop iterates 10 times so above code hits in database 10 times to get attribute text ? Commented Dec 22, 2022 at 18:03
0

We normally use this for printing labels in options attributes, which may seem lighter than posted code

$_product->getAttributeText($attributecode);

But if we check what this does we can see

public function getAttributeText($attributeCode)
{
    return $this->getResource()->getAttribute($attributeCode)->getSource()->getOptionText(
        $this->getData($attributeCode)
    );
}

Which seems practically the same as posted code, so I don't think you could find a better approach in terms of performance, apart from getting the value you want directly with a SQL query which would be obviously the lightest & fastest approach

2
  • my question is if we use $_product->getAttributeText($attributecode) code in for loop and for loop iterates 10 times so above code hits in database 10 times to get attribute text ? Commented Dec 22, 2022 at 18:02
  • Not sure how much calls would result, you can use Magento profiler & see :) Commented Dec 23, 2022 at 8:57

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.