How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2

 <?php

use Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';


try{

    $bootstrap = Bootstrap::create(BP, $_SERVER);

    $objectManager = $bootstrap->getObjectManager();

    $state = $objectManager->get('Magento\Framework\App\State');

    $state->setAreaCode('frontend');


    $productIds = ['1','2']; // Product Ids


    foreach($productIds as $productId){

        $urls = [];

        $product = $objectManager->create(\Magento\Catalog\Model\Product::class)->load($productId);

        $urls[] = $objectManager->create(\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class)->generate($product);

 

        $urlPersist = $objectManager->create(\Magento\UrlRewrite\Model\UrlPersistInterface::class);

        $urlPersist->replace(array_merge([], ...$urls));

    

        $product->setStoreId(1); 

        $product->setWebsiteIds(['1']);  

        $product->save();        

    }

    echo "Product URL generated successfully";  

}

catch(\Exception $e)

{

    print_r($e->getMessage());

}


?>

Comments

Popular posts from this blog

Add Admin User name and Action name in Order Comment Section through Action Performed from Sales Order Grid in Magento 2

How to Update Product Stock Programmatically in Magento 2

How to Set and Get Cookie in Magento 2