Showing a Product’s Brand (or Any Dropdown Attribute) in Magento 2

Showing a Product’s Brand (or Any Dropdown Attribute) in Magento 2

Dropdown attributes like brand store an option ID, so printing them directly shows a number instead of a name. These three steps display the readable label in the place you want.

1. Add a block in catalog_product_view.xml

<block class="Magento\Catalog\Block\Product\View\Description" name="page.main.brand" template="Magento_Catalog::product/view/brand.phtml">
      	<arguments>
        <argument name="at_call" xsi:type="string">getBrand</argument>
        <argument name="at_code" xsi:type="string">brand</argument>
        <argument name="css_class" xsi:type="string">brand</argument>
        <argument name="at_label" xsi:type="string">default</argument>
        <argument name="add_attribute" xsi:type="string">itemprop="brand"</argument>
      </arguments>
      </block>

2. Move it into position

This places it just below the product title:

<move element="page.main.brand" destination="product.info.main" after="page.main.title"/>

3. Write the template

Use getAttributeText() to turn the option ID into its label:

<?php
/**
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

/**
 * Product description template
 *
 * @var $block \Magento\Catalog\Block\Product\View\Description
 */
?>
<?php
$_helper = $this->helper('Magento\Catalog\Helper\Output');
$_product = $block->getProduct();
 
$_code = $block->getAtCode();
$_className = $block->getCssClass();
$_attributeLabel = $block->getAtLabel();
$_attributeType = $block->getAtType();
$_attributeAddAttribute = $block->getAddAttribute();
 
if ($_attributeLabel && $_attributeLabel == 'default') {
$_attributeLabel = $_product->getResource()->getAttribute($_code)->getFrontendLabel();
}
 
$_attributeValue =$_product->getResource()->getAttribute($_code)->getFrontend()->getValue($_product);
 
?>
 
<?php if ($_attributeValue): ?>
<div class="product attibute <?php echo $_className?>">
<?php /*?><?php if ($_attributeLabel != 'none'): ?><strong class="type"><?php echo $_attributeLabel?></strong><?php endif; ?><?php */?>
<div class="value" <?php echo $_attributeAddAttribute;?>><?php echo $_attributeValue; ?></div>
</div>
<?php endif; ?>

Want this done for you? Find out more about our Magento development service.

Keep reading

Related articles

All articles

Need a hand?

Stuck on something similar?
We can fix it with you.

Send us the problem. A senior developer reads every message and replies within one working day.