Magento 2 — Add attributes to mini cart list

Step by step instructions with examples to add a custom attribute to the mini cart item list in Magento 2 using plugins the correct way.

Shane Blandford
2 min readAug 29, 2018

Recently the team at Orange Collar Media have been working on a custom Magento 2 module for a client that involves modifying the item list in the mini cart. To do this correctly is a bit more involved in Magento 2 than it used to be.

This is due to the mini cart being rendered by the knockout templates. The list of product attributes is built by a function called doGetItemData() located in the file vendor/magento/module-checkout/CustomerData/DefaultItem.php

Quickly looking at this function and it is clear that to get our custom attribute added we need to modify the array being produced.

The correct way to update this array is to create a plugin in our module. However, the doGetItemData()function is not public so we can not intercept this exact function.

Looking at the DefaultItem class we can see that it extends the AbstractItem class. In this class the function getItemData()is a public function and it calls the doGetItemData() function.

This plugin will fire after the getItemData() function and add the custom attribute to the array.

Step 1 — Define the Plugin

In your module di.xml file add the following

<type name="Magento\Checkout\CustomerData\AbstractItem"> <plugin name="Vendor_Module_DefaultItemPlugin" type="Vendor\Module\Plugin\DefaultItemPlugin" sortOrder="10" disabled="false" /> </type>

So it looks like this

Step 2 — Create the Plugin

Create a new plugin class in Vendor\Module\Plugin\DefaultItemPlugin.php

<?php namespace Vendor\Module\Plugin; class DefaultItemPlugin { public function afterGetItemData( \Magento\Checkout\CustomerData\AbstractItem $subject, $result, \Magento\Quote\Model\Quote\Item $item) { $data['customattribute'] = $item->getProduct()->getAttributeText('customattribute'); return \array_merge( $result, $data ); } }

It should look like this class

Step 3 — Update your template file

Then add this code to your template file.

<Vendor>/<theme>/Magento_Checkout/frontend/web/templates/minicart/item/default.html

<! — ko if: customattribute –>

<! — ko text: customattribute –><! — /ko –>

<! — /ko –>

Originally published at www.orangecollarmedia.com on August 29, 2018.

--

--

Shane Blandford
Shane Blandford

No responses yet