How To

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

Hello Magento Friends,

In this Magento 2 blog illustration, I will explain How to Add URL Rewrite for Product Programmatically using Root Script in Magento 2. 

URL rewrite involves modifying the URL of website pages to create more user-friendly URLs. In Magento 2, you can Add URL Rewrite from Admin or Add URL Rewrite Programmatically.

By default, Magento generates the URL key for a product based on its name or specified attribute values. However, you can modify or override the URL key to create a custom URL for a product using the URL rewrite functionality.

Product URL rewrite allows you to customize the URL of the product page of your Magento 2 store. It enables you to create SEO-friendly URLs, manage URL redirects, and improve the overall user experience by providing more descriptive and memorable URLs for your products. They play a crucial role in SEO optimization and ensuring that customers can access product pages through clean and meaningful URLs.

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

Step 1: Create Producturl.php in your Magento root directory and add the following code.

<?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());
}

?>

Product URL will be generated if not available in the current URL rewrite table.

Conclusion:

This way, you can add product URL rewrite programmatically using root script in Magento 2. If you face any issues, share them with me through the comment box without any hesitation. I will be quick to provide you with the solution. Moreover, share the tutorial with your friends to help them add product URL rewrites in their Magento 2 stores. 

Happy Coding!

Click to rate this post!
[Total: 1 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate 🎖️ Certified Magento Developer👨‍💻. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.🏏

Recent Posts

How to Integrate ChatGPT with Laravel Application?

In this guide, we'll explore how to integrate ChatGPT, an AI-powered chatbot, with a Laravel…

15 hours ago

What are Net Sales? How to Calculate Your Net Sales?

In the world of business, understanding financial metrics is crucial for making informed decisions and…

3 days ago

Magento 2 Extensions Digest April 2024 (New Release & Updates)

Welcome to the MageComp Monthly Digest, where we bring you the latest updates, releases, and…

3 days ago

The ABCs of Geofencing: Definition, Features and Uses

In this era, businesses are always on the lookout for ways to engage with their…

4 days ago

How to Delete Product Variant in a Shopify Remix App using GraphQL Mutations?

Managing a Shopify store efficiently involves keeping your product catalog organized. This includes removing outdated…

5 days ago

6 Innovative Tools Revolutionizing E-Commerce Operations

E-commerce has transformed the way consumers shop for products and services and interact with businesses.…

7 days ago