How to add URL Rewrites programmatically in Magento 2

URL Rewrites programmatically in magento is the best solutions for online retailers as you who want to truly build a huge number of the traffics of your websites. The function of rewriting the URL is permitting you producing 301 redirects in to Magento 2 by programmatically.

URL redirect

URL redirect is a main 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

So, if you are marveling how to continue working with the existing visitor at the current site while you are planning to construct a new site with more efficiencies, the best answer is creating the search redirection through the redirect   301.

Here the following steps help you to add URL Rewrites programmatically in Magento 2

Step 1: Create constructor file

Step 2: Build 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

*/

public function __construct(

    Context $context,

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

) {

    $this->_eavAttributeFactory = $eavAttributeFactory;

    parent::__construct(

        $context

    );

}

 Build custom URL rewrite in execute method

The actual website URL is www.example.com/customModule/customController/customAction, but you want to implement 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);
/* this url is not created by system so set as 0 */
$urlRewriteModel->setIsSystem(0);
/* unique identifier - set random unique value to id path */
$urlRewriteModel->setIdPath(rand(1, 100000));
/* set actual url path to target path field */
$urlRewriteModel->setTargetPath("www.example.com/customModule/customController/customAction");
/* set requested path which you want to create */
$urlRewriteModel->setRequestPath("www.example.com/xyz");
/* set current store id */
$urlRewriteModel->save();

 These are the following steps help you to add URL Rewrites programmatically in Magento 2

Last Update: April 5, 2018  

February 20, 2018   3926   Nandini R    Magento    
Total 4 Votes:
1

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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

Facebook
Google+
http://www.webnexs.com/blog/kb/add-url-rewrites-programmatically-magento-2
Twitter
LinkedIn