How to add URL Rewrites programmatically in Magento 2

Image result for magento 2

 

In this blog, we discuss about URL Rewrites programmatically in magento 2, it is the best solutions for online vendors as you who desire to truly build a huge number of the traffics of your websites. The function of rewrite the URL is allowing you producing 301 redirects in to Magento 2 by programmatically.

URL redirect

URL redirect is a major term in SEO and it is used for navigating the visitors to any link store owners expect. There are two main type of redirect

  • 301 redirect
  • 302 redirect

Therefore, if you are wondering how to maintain working with the existing visitor at the current site while you are planning to make a new site with more efficiencies, creating the search redirection through the redirect 301 is the best answer.

The below mentioned steps help you to add URL Rewrites programmatically in Magento 2

Step 1: Create constructor file

Step 2: Construct custom URL rewrite in execute method

Create constructor file

/**

* @var \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory

*/

protected $_urlRewriteFactory;

/**

* @param Context $context

* @param \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory

*/

ublic function __construct(

    Context $context,

    \Magento\UrlRewrite\Model\ResourceModel\UrlRewriteFactory $urlRewriteFactory

) {

    $this->_eavAttributeFactory = $eavAttributeFactory;

    parent::__construct(

        $context

    );

}

 Construct custom URL rewrite in execute method

The definite website URL is  www.example.com/customModule/customController/customAction, but you want to execute the URL as www.example.com/xyz(requested URL) then you can build by the following method:

$urlRewriteModel = $this->_urlRewriteFactory->create ()

/* set current store id */

$urlRewriteModel->setStoreId(1);

/* the following url is not formed by system so set as 0 */

$urlRewriteModel->setIsSystem(0);

/* unique identifier - place random unique value to id path */

$urlRewriteModel->setIdPath(rand(1, 100000));

/* place actual url path to target path field */

$urlRewriteModel->setTargetPath("www.example.com/customModule/customController/customAction");

/* set requested path which you desire to form */

$urlRewriteModel->setRequestPath("www.example.com/xyz");

/* set current store id */

$urlRewriteModel->save();

I hope, these steps help you to add URL Rewrites programmatically in Magento 2

Last Update: March 5, 2019  

February 20, 2018   4705   Nandini R    Magento    
Total 6 Votes:
1

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

8 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
INSTAGRAM
LinkedIn