Magento 2: How to Show Custom Attribute in Minicart

Hello Magento Friends,

In Magento 2, the minicart is a great way for your customers to get an overview of what products they have in their cart without leaving the current page. The default minicart shows product name, quantity, price, and a small thumbnail image. 

Magento version upgrade

However, what happens if you want to quickly show custom product attributes like Color, Size or a specific feature of the product right from the minicart? This will improve the customer shopping experience by giving them immediate product details, while also decreasing cart abandonment. 

In this blog, we’ll show you how to display a custom attribute in the Magento 2 minicart.

Steps to Show Custom Attribute in Magento 2 Minicart:

Step 1: Create the requirejs-config.js file at the given path.

{{magento_root}}\app\code\Vendor\Extension\view\frontend\requirejs-config.js

Then add the code as follows

var config = {
    map: {
        '*': {
            'Magento_Checkout/template/minicart/item/default.html': 'Vendor_Extension/template/minicart/item/default.html'
        }
    }
};

Step 2: Create the default.html file at the given path.

{{magento_root}}\app\code\Vendor\Extension\view\frontend\web\template\minicart\item\default.html

Now, add the code as given below

<li class="item product product-item" data-role="product-item">
    <div class="product">
        <!-- ko if: product_has_url -->
        <a data-bind="attr: {href: product_url, title: product_name}" tabindex="-1" class="product-item-photo">
            <!-- ko foreach: $parent.getRegion('itemImage') -->
                <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
            <!-- /ko -->
        </a>
        <!-- /ko -->
        <!-- ko ifnot: product_has_url -->
        <span class="product-item-photo">
            <!-- ko foreach: $parent.getRegion('itemImage') -->
                <!-- ko template: {name: getTemplate(), data: item.product_image} --><!-- /ko -->
            <!-- /ko -->
        </span>
        <!-- /ko -->

        <div class="product-item-details">
            <strong class="product-item-name">
                <!-- ko if: product_has_url -->
                <a data-bind="attr: {href: product_url}, html: $parent.getProductNameUnsanitizedHtml(product_name)"></a>
                <!-- /ko -->
                <!-- ko ifnot: product_has_url -->
                    <span data-bind="html: $parent.getProductNameUnsanitizedHtml(product_name)"></span>
                <!-- /ko -->
            </strong>
            <!-- ko if: item.custom_value -->
        <div data-bind="html: 'Custom Value: ' + item.custom_value"></div>
        <!-- /ko -->

            <!-- ko if: options.length -->
            <div class="product options" data-mage-init='{"collapsible":{"openedState": "active", "saveState": false}}'>
                <span data-role="title" class="toggle"><!-- ko i18n: 'See Details' --><!-- /ko --></span>

                <div data-role="content" class="content">
                    <strong class="subtitle"><!-- ko i18n: 'Options Details' --><!-- /ko --></strong>
                    <dl class="product options list">
                        <!-- ko foreach: { data: options, as: 'option' } -->
                        <dt class="label"><!-- ko text: option.label --><!-- /ko --></dt>
                        <dd class="values">
                            <!-- ko if: Array.isArray(option.value) -->
                                <span data-bind="html: $parents[1].getOptionValueUnsanitizedHtml(option.value.join('<br>'))"></span>
                            <!-- /ko -->
                            <!-- ko if: (!Array.isArray(option.value) && ['file', 'html'].includes(option.option_type)) -->
                                <span data-bind="html: $parents[1].getOptionValueUnsanitizedHtml(option.value)"></span>
                            <!-- /ko -->
                            <!-- ko if: (!Array.isArray(option.value) && !['file', 'html'].includes(option.option_type)) -->
                            <span data-bind="text: option.value"></span>
                            <!-- /ko -->
                        </dd>
                        <!-- /ko -->
                    </dl>
                </div>
            </div>
            <!-- /ko -->

            <div class="product-item-pricing">
                <!-- ko if: canApplyMsrp -->

                <div class="details-map">
                    <span class="label" data-bind="i18n: 'Price'"></span>
                    <span class="value" data-bind="i18n: 'See price before order confirmation.'"></span>
                </div>
                <!-- /ko -->
                <!-- ko ifnot: canApplyMsrp -->
                <!-- ko foreach: $parent.getRegion('priceSidebar') -->
                    <!-- ko template: {name: getTemplate(), data: item.product_price, as: 'price'} --><!-- /ko -->
                <!-- /ko -->
                <!-- /ko -->

                <div class="details-qty qty">
                    <label class="label" data-bind="i18n: 'Qty', attr: {
                           for: 'cart-item-'+item_id+'-qty'}"></label>
                    <input data-bind="attr: {
                           id: 'cart-item-'+item_id+'-qty',
                           'data-cart-item': item_id,
                           'data-item-qty': qty,
                           'data-cart-item-id': product_sku
                           }, value: qty"
                           type="number"
                           size="4"
                           class="item-qty cart-item-qty"/>
                <button data-bind="attr: {
                           id: 'update-cart-item-'+item_id,
                           'data-cart-item': item_id,
                           title: $t('Update')
                           }"
                            class="update-cart-item"
                            style="display: none">
                        <span data-bind="i18n: 'Update'"></span>
                    </button>
                </div>
            </div>

            <div class="product actions">
                <!-- ko if: is_visible_in_site_visibility -->
                <div class="primary">
                    <a data-bind="attr: {href: configure_url, title: $t('Edit item')}" class="action edit">
                        <span data-bind="i18n: 'Edit'"></span>
                    </a>
                </div>
                <!-- /ko -->
                <div class="secondary">
                    <a href="#" data-bind="attr: {'data-cart-item': item_id, title: $t('Remove item')}"
                       class="action delete">
                        <span data-bind="i18n: 'Remove'"></span>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <div class="message notice" if="$data.message">
        <div data-bind="text: $data.message"></div>
    </div>
</li>

Step 3: Create the di.xml file at the given path below.

{{magento_root}}\app\code\Vendor\Extension\etc\di.xml

After that, add the following code

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\CustomerData\DefaultItem">
        <plugin name="add_custom_label_to_quote_item" type="Vendor\Extension\Plugin\QuoteItemFactoryPlugin" />
    </type>
</config>

Step 4: Create the QuoteItemFactoryPlugin.php file at the given file path.

{{magento_root}}\app\code\Vendor\Extension\Plugin\QuoteItemFactoryPlugin.php

At last, include the below-mentioned piece of code

<?php

namespace Vendor\Extension\Plugin;

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Model\Product;
use Magento\Quote\Model\Quote\Item;

class QuoteItemFactoryPlugin
{
    protected $_productloader;

    public function __construct(
        \Magento\Catalog\Model\ProductFactory $_productloader
    )
    {
        $this->_productloader = $_productloader;
    }

    public function aroundGetItemData($subject, \Closure $proceed, Item $item)
    {
        $data = $proceed($item);

        /** @var Product $product */
        $product = $this->_productloader->create()->load($item->getProduct()->getId());
	//get your product attribute here
        $atts = [
            "custom_value" => $product->getNewproduct()
        ];

        return array_merge($data, $atts);
    }
}

Output:

Conclusion:

Adding custom attributes to the Magento 2 minicart is a simple yet powerful enhancement that improves the shopping experience. Whether you want to show product variations, manufacturing details, or custom messages, this method ensures customers have all the important information right where they need it.

Hire Magento Programmer

Happy Coding!

FAQ

  1. When I make these changes do I have to clear the cache?

To apply the changes, you will need to run all the following standard commands: 

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f
php bin/magento setup:di:compile
php bin/magento cache:clean
php bin/magento cache:flush
  1. Can I show custom attributes for only some products?

Yes, you can just add a condition to your plugin that looks for a product type or a value of a certain attribute before adding the info to the minicart data.

  1. Can I style the custom attribute text differently in the minicart?

Yes, absolutely. You can create a CSS class in your template file, and then style it via your theme’s CSS.

Previous Article

Laravel 12: Import Large CSV File into Database Example

Next Article

Mastering Shopify App Proxy Components in Remix: A Beginner-Friendly Guide

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨