Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento 2 - change url key programmatically

Tags:

magento2

Is there a way to generate URL Keys for all products and save them using a script?

I deleted all URL keys for products from database, but now I want to generate them again using a script.

// Edit: I need to do this in Magento 2. Forgot to specify.

I got this until now:

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);    
$obj = $bootstrap->getObjectManager();
$deploymentConfig = $obj->get('Magento\Framework\App\DeploymentConfig');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

$repo = $objectManager->get('Magento\Catalog\Model\ProductRepository');

$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
    $name = $product->getName();
    $url = preg_replace('#[^0-9a-z]+#i', '-', $name);
    $url = strtolower($url);
    echo $url;
    $pr = $repo->getById($product->getId());
    $pr->setUrlKey($url);

    $repo->save($pr);
    break;
}

But I get this error:

Fatal error: Call to undefined function Magento\Catalog\Model\Config\Source\Product\Options__() in /home2/magazi70/public_html/vendor/magento/module-catalog/Model/Config/Source/Product/Options/Price.php on line 23

like image 303
Filip Avatar asked Apr 30 '26 10:04

Filip


1 Answers

<?php
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);    
$obj = $bootstrap->getObjectManager();
$deploymentConfig = $obj->get('Magento\Framework\App\DeploymentConfig');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('\Magento\Catalog\Model\Product');

$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){

    $product = $objectManager->create('\Magento\Catalog\Model\Product')->load($product->getId());
    $name = $product->getName();
    $url = preg_replace('#[^0-9a-z]+#i', '-', $name);
    $url = strtolower($url);

    $product ->setUrlKey($url);
    $product->save($pr);

}
like image 98
Baharuni Asif Avatar answered May 03 '26 07:05

Baharuni Asif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!