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.
We use cookies to help improve our services, make personal offers, and enhance your experience. If you do not accept optional cookies below, your experience may be affected. If you want to know more, please read the Cookie Policy
Please select and accept your Cookies Group
Cookie Name | Cookie Provider | Cookie Description | Cookie Lifetime | Cookie Type |
---|---|---|---|---|
Login and Registration Form