1

I have import categories via CSV and I would like to import category image from external URL. I have used Magento ver. 2.3.1

I have tried to save images to the category but can't able to get success.

If any have idea how to import category image from external URL then let me know.

Any help would be appreciated. Thanks.

0

Please check below code. I hope it will help you.

use \Magento\Framework\App\Bootstrap;
include('../app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$state = $objectManager->get('\Magento\Framework\App\State');   

$websiteId = $storeManager->getWebsite()->getWebsiteId();
$storeId = $store->getStoreId();
$rootNodeId = $store->getRootCategoryId();
$rootCat = $objectManager->get('Magento\Catalog\Model\Category');

$cat_info = $rootCat->load($rootNodeId);
$categorys=array('Living','Sofa','Tables','Beds');// Category Names
foreach($categorys as $cat){
    $name=ucfirst($cat);

    $url=strtolower($cat);

    $cleanurl = trim(preg_replace('/ +/', ", preg_replace(‘/[^A-Za-z0-9 ]/’, ", urldecode(html_entity_decode(strip_tags($url))))));

    $categoryFactory=$objectManager->get(‘\Magento\Catalog\Model\CategoryFactory’);

    $categoryTmp = $categoryFactory->create();$categoryTmp->setName($name);
    $categoryTmp->setIsActive(true);$categoryTmp->setUrlKey($cleanurl);
    $categoryTmp->setData('description', 'description');
    $categoryTmp->setParentId($rootCat->getId());
    $mediaAttribute = array ('image', 'small_image', 'thumbnail');
    $categoryTmp->setImage('/category.png', $mediaAttribute, true, false);// Path pub/meida/catalog/category/category.png
    $categoryTmp->setStoreId($storeId);
    $categoryTmp->setPath($rootCat->getPath());
    $categoryTmp->save();

}
  • Thanks for your help. That way only save image name. But How can copy image from external URL to pub/media/catalog/category/ directory. – Kirti Nariya Jun 26 at 6:43
  • via zip we need to extract in location. – Anas Mansuri Jun 26 at 6:44
  • You are right that way already working. I have need to put external image path from CSV and import it to the category. – Kirti Nariya Jun 26 at 6:49
  • i suggest to buy extension for that. – Anas Mansuri Jun 26 at 6:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.