How to Add URL Rewrite Programmatically in Magento 2

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

    }

}

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