Hello Magento Friends,
In today’s Magento 2 tutorial, I am going to figure out How to Add URL Rewrite Programmatically in Magento 2.
You may require customers to redirect from the old URL to a new address. If the old address is not redirected to the new address, you may lose website traffic. Enabling URL rewrite for Magento 2 helps to redirect customers to new URL addresses easily. URL rewrite is used to make existing URLs more search-friendly.
Check How to Configure and Manage URL Rewrite in Magento 2.
Here we will learn about Adding URL Rewrite Programmatically in Magento 2.
Let’s check the steps
Steps to Add URL Rewrite Programmatically in Magento 2:
Step 1: To generate the constructor, you have to use the below block of code in your controller file. Here, we have used the Magento\UrlRewrite\Model\UrlRewriteFactory instance and create its object($urlRewriteFactory).
<?php namespace Vendor\Extension\Controller; use Magento\Framework\App\Action\Context; class CustomController { protected $urlRewriteFactory; public function __construct( Context $context, \Magento\UrlRewrite\Model\UrlRewriteFactory $urlRewriteFactory) { $this->urlRewriteFactory = $urlRewriteFactory; parent::__construct($context); } public function execute() { $urlRewrite = $this->urlRewriteFactory->create(); /*if you want to rewrite url for “custom” set entity type*/ $urlRewrite->setEntityType('custom'); /*set current store ID */ $urlRewrite->setStoreId(1); /*set 0 as this url is not created by system */ $urlRewrite->setIsSystem(0); /* unique identifier - place random unique value to ID path */ $urlRewrite->setIdPath(rand(1, 100000)); /* set actual url path to target path field */ $urlRewrite->setTargetPath("https://yourdomainname/customModule/customController/customAction"); /* set requested path which you want to create */ $urlRewrite->setRequestPath("https://yourdomainname/abc"); /* set the type of Redirect */ $urlRewrite->setRedirectType(301); /* save URL rewrite rule */ $urlRewrite->save(); } }
Conclusion:
Hence, this way you can Add URL Rewrite Programmatically in Magento 2. If you have any queries feel free to ask me. Share the article with other developers.
Happy Coding!