Magento, Magento 2

Magento 2 : Generate Product URL Rewrites Programmatically

How to Generate Product URL Rewrites Programmatically in Magento 2

In this Tutorial, Today I will explain you how to generate product url rewrites in Magento 2 Programmatically. Sometimes, product is created but URL is not generated. Hence, the product page URL will be return as 404 & it will be impact on SEO score. It will also down your website SEO as well. So, if you want to generate product url rewrites programmatically then you can use this below script.

You may also like this :

Create ProductUrlGenerator.php file at your root directory and paste the below code :

<?php
/**
 * Created By : Rohan Hapani
 */
use Magento\Framework\App\Bootstrap;

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

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$productIds = ['1,2']; // set your product Ids
$collection = $objectManager->create(\Magento\Catalog\Model\Product::class)->getCollection()
             ->addFieldToFilter('entity_id',['in' => $productIds]);
$urls = [];
foreach ($collection as $product) {
    $product->setStoreId(1);  // set here your store id.
    $urls[] = $objectManager->create(\Magento\CatalogUrlRewrite\Model\ProductUrlRewriteGenerator::class)->generate($product);
}
$urlPersist = $objectManager->create(\Magento\UrlRewrite\Model\UrlPersistInterface::class);
$urlPersist->replace(array_merge([], ...$urls));

$productCollectionFactory = $objectManager->create(\Magento\Catalog\Model\ResourceModel\Product\Collection::class);
$productcollection = $productCollectionFactory->addAttributeToSelect('*')
        ->addFieldToFilter('entity_id',['in' => $productIds])
        ->load();
foreach ($productcollection as $product) {
    $product->setStoreId(1); // set here your store id.
    $product->setWebsiteIds(['1']);  // set here your website id.
    $product->save();
}
echo "Product URL generated successfully.";
?>

open terminal and execute this below command to generate product URL.

php ProductUrlGenerator.php

You can execute URL as well like http://m244.com/ProductUrlGenerator.php and URL will be successfully generated.

You can check result in url_rewrites table in your database. or if you want to check in admin then, you can check from Marketing -> SEO & Search -> URL Rewrites grid.

That’s it !!!

I hope this blog is easy to understand about how to generate product url rewrites in Magento 2 Programmatically. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.

Keep liking and sharing !!

Tagged ,