How to get the current URL in Magento 2 blocks and templates?

Sometimes you need to get the current URL in your Magento 2 block or templates or get product URL in Magento 2. In Magento 2 to get store URL we usually work with the getCurrentUrl() function. Let’s see what steps you need to undertake.

→ Working on custom development? Our team is ready to help you with challenging tasks

Step 1. First of all, you need to create a new block in your plugin. For example, we have made Block/Test.php with the following code using the Magento framework view element template:

<?php

namespace <Vendor>\<Module>\Block;

use Magento\Store\Model\StoreManagerInterface;

class Test extends \Magento\Framework\View\Element\Template
{
/**
* @var QuoteEmail
*/
private $storeManager;

public function __construct(
StoreManagerInterface $storeManager,
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
$this->storeManager = $storeManager;
parent::__construct($context, $data);
}

public function getCurrentUrl() {
return $this->storeManager->getStore()->getCurrentUrl();
}


}

Step 2. Next, you need to create a template file for this block in the view/frontend/templates/ folder. In our case, we have made test.phtml. There are 2 options for how you can get the current URL parameters in the Magento template. See the example below:

<?php
//1 way
$block->escapeUrl($block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]));
//2 way
$block->escapeUrl($block->getCurrentUrl());
?>

It’s better to use the second way, but the first is acceptable too. Don’t forget to clean the cache after saving the changes.


Helpful hint: To avoid the problem of numerous links for the same product or too long paths to your prod pages, try out this Unique Product URL. Set up automatic redirects from non-essential URLs to the main ones, ignore secondary categories in a prod path to shorten and, therefore, optimize the paths not only for users but also for search engines.

 

How can we help you?

Didn’t you find the answer to your question? We are always happy to help you out.