Url friendly for custom module

You want to add friendly URLs for your custom module like product URLs in Magento 2. This short tutorial will help you doing that. In Magento 2 database, there is one table to store data about url “url_rewrite”. This table map target_path and request_path.

For example:

  • Target_path: “vendor/newshop/testimonials”
  • Request_path: “newshop/testimonials”

Step 1: Uou just need to add a new record to table “url_rewrite”:

$urlRewrite = $this->_objectManager->create('Magento\UrlRewrite\Model\UrlRewrite');
$urlRewrite->setStoreId($getCurrentStoreId)
           ->setIsSystem(0)
           ->setTargetPath("newshop/testimonials")
           ->setRequestPath("vendor/newshop/testimonials")
           ->save(); 

Step 2: Write a method getRewriteUrl with param “$targetPath”

public function getRewriteUrl($targetPath)
    {
        $requestPath = $this->_urlBuilder->getUrl(
            '',
            [
                '_direct' => $targetPath,
                '_secure' => $this->_request->isSecure(),
            ]
        );
       
        $urlColl = $this->_objectManager->create('Magento\UrlRewrite\Model\UrlRewrite')
            ->getCollection()
            ->addFieldToFilter('target_path', $targetPath)
            ->addFieldToFilter('store_id', $this->getCurrentStoreId());
        foreach ($urlColl as $value) {
            $requestPath = $this->_urlBuilder->getUrl(
                '',
                [
                    '_direct' => $value->getRequestPath(),
                    '_secure' => $this->_request->isSecure(),
                ]
            );
        }

        return $requestPath;
    }

Step 3: Use method above in phtml template

You can use $block->getRewriteUrl(‘newshop/testimonials’)  to get a correct link.

 

 

 

Leave a Reply

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