Get a Product Attribute in Mini Cart

Would you like to display another product attribute or a custom one in mini cart? Let's see together how you can do that!

Further to our last post about how you can get another product attribute or a custom one in cart, today we will see how you can do the same but in mini cart. In our example we will display next to the product name, the product manufacturer. First of all we have to include the manufacturer attribute in the quote item as in not included by default. So like we did in our last post, we create a file under app/code/MageVision/Blog10/etc/catalog_attributes.xml and we add the following code.

The vendor/magento/module-checkout/CustomerData/DefaultItem.php class is used for retrieving data for each item in mini cart.

In this class the function doGetItemData() is returning an array of the item's data. As we can see the product manufacturer data is not included in that array. So we have to override this function. Better way to do that is by creating a plugin. Unfortunately this function is protected, so this is not possible. But as we can see the vendor/magento/module-checkout/CustomerData/DefaultItem.php class extends from the vendor/magento/module-checkout/CustomerData/AbstractItem.php class where the public function getItemData() calls our doGetItemData() function. That means we can create a plugin for the getItemData() function and extend the data array by adding the product manufacturer.

Create a di.xml file to declare the plugin.

Create a class under /app/code/MageVision/Blog10/Plugin/Checkout/CustomerData/DefaultItem.php  with an aroundGetItemData() function.

Now that we have the data that we need to display, we have to override the default template. As we can see in the /vendor/magento/module-checkout/view/frontend/layout/checkout_cart_sidebar_item_renderers.xml file, which is responsible for rendering the mini cart items, the template that is used is the /vendor/magento/module-checkout/view/frontend/web/template/minicart/item/default.html.

To override the files above, we create a checkout_cart_sidebar_item_renderers.xml file under /app/code/MageVision/Blog10/view/frontend/layout/checkout_cart_sidebar_item_renderers.xml adding the code below.

Also we copy the /vendor/magento/module-checkout/view/frontend/web/template/minicart/item/default.html template file under /app/code/MageVision/Blog10/view/frontend/web/template/minicart/item/default.html and we add the product manufacturer data next to the product name by adding the code below.

So after adding a product to cart, the mini cart will look like

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!