I need to change all my product URLs and I would like to use a code snippet to use it. All I need is a simple code which is Magento 2 compatible and will change the URL for one product then saves it. I have this so far:
<?php
use \Magento\Framework\App\Bootstrap;
include('/var/www/html/app/bootstrap.php');
$bootstrap = 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');
$product = $objectManager->create('\Magento\Catalog\Model\Product')->load(2933);
$name = $product->getName();
print $name;
$url="new-product-url";
$product ->setUrlKey($url);
$objectManager->get('\Magento\Catalog\Model\Product')->save($product);
#$product->save();
?>
The code goes as far as the URL change then it fails with:
PHP Fatal error: Uncaught Magento\Framework\Exception\LocalizedException: Area code is not set in /var/www/html/vendor/magento/framework/App/State.php:153
Stack trace:
#0 /var/www/html/vendor/magento/module-catalog/Model/Product.php(2415): Magento\Framework\App\State->getAreaCode()
#1 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(58): Magento\Catalog\Model\Product->getIdentities()
#2 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Catalog\Model\Product\Interceptor->___callParent('getIdentities', Array)
#3 /var/www/html/vendor/magento/framework/Interception/Interceptor.php(153): Magento\Catalog\Model\Product\Interceptor->Magento\Framework\Interception\{closure}()
#4 /var/www/html/generated/code/Magento/Catalog/Model/Product/Interceptor.php(52): Magento\Catalog\Model\Product\Interceptor->___callPlugins('getIdentities', Array, Array)
#5 /var/www/html/vendor/magento/framework/App/Cache/Tag/Strategy/Identifier.php(25): Magento\Catalog\Model\Product\Interceptor->getIdentities( in /var/www/html/vendor/magento/framework/App/State.php on line 153
I am unsure why would I be defining any area codes when I am only changing a product not an order or a customer?!