In this topic we will do How to Change Product Image in Minicart
Step 1: Create di.xml file
Step 2: Create Image.php file
Product image in minicart will getten to show by function doGetItemData()
in Magento\Checkout\CustomerData\DefaultItem
class but this function is protected, so we cannot use plugin on it. Instead, it extends from Magento\Checkout\CustomerData\AbstractItem
and use function getItemData()
First We need to create registration and module file as per structure of magento 2 then follow below steps.
Step 1: Create di.xml file
Create di.xml file in app/code/[Name_Space]/[Your_Module]/etc/frontend
<?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\AbstractItem">
<plugin name="Change_Product_Image_In_Minicart" type="[Name_Space]\[Your_Module]\Plugin\Minicart\Image" sortOrder="1"/>
</type>
</config>
Step 2: Create Image.php file
Create Image.php file in app/code/[Name_Space]\[Your_Module]\Plugin\Minicart
<?php
namespace [Name_Space]\[Your_Module]\Plugin\Minicart;
class Image
{
public function aroundGetItemData($subject, $proceed, $item)
{
$result = $proceed($item);
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->create('Magento\Catalog\Model\Product')->load($result['product_id']);
/* thum url */
$storeManager = $objectManager->create('Magento\Store\Model\StoreManagerInterface');
$currentStore = $storeManager->getStore();
$mediaUrl = $currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
if($product->getThumbnail()){
$result['product_image']['src'] = $mediaUrl.$product->getThumbnail();
}
else{
$result['product_image']['src'];
}
return $result;
}
}