2

I try to retrieve one custom attributes for a product and print in title.phtml. I have followed all the steps for create a custom attribute and add it to a group correctly and it appears in admin panel and I can insert my custom value. The problem comes when I try to retrieve the new custom attribute using

$_product = $this->getProduct();
$sample = $_product->getCustomAttribute('sample');

If I print the var_dump of $_product the custom attribute is missing. Thanks

1 Answer 1

1

Make sure when you add your custom product attribute, you have to add the visible_on_front property with value true, eg:

$eavSetup->addAttribute(
    Product::ENTITY,
    'sample',
    [
        ....
        'visible_on_front' => true
    ]
);

Assume you custom product atribute code is sample, to get your custom product attribute value, use $product->getData('sample') or $product->getSample().

If that code does not work in your phtml file, try to use code below:

echo $this->helper(Magento\Catalog\Helper\Output::class)->productAttribute(
    $block->getProduct(),
    $block->getProduct()->getSample(),
    'sample'
)

or

echo $attributeValue = $product->getResource()->getAttribute('sample')->getFrontend()->getValue($product);

8
  • Already tried but still, it is not showing cos does not exist when I print the var_dump. @pawan in a similar topic target to use Magento\Catalog\Api\ProductRepositoryInterface Commented Oct 19, 2022 at 9:29
  • I don't think you need to use Magento\Catalog\Api\ProductRepositoryInterface, did you try all 3 ways above?
    – Tu Van
    Commented Oct 19, 2022 at 10:17
  • Yes, I did with not success. btw I always reindex in the end Commented Oct 19, 2022 at 10:43
  • Which is the block used for your phtml file?
    – Tu Van
    Commented Oct 19, 2022 at 10:45
  • \Magento\Catalog\Model\Product $_product Commented Oct 19, 2022 at 10:50

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.