Search
×
Log in or create an account
If you have an account with us, please log in.

You have no items in your shopping cart.

Frequently Asked Questions

How can we help you?

banner image

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. For this, we usually work with the getCurrentUrl() function. Let’s see what steps you need to undertake.

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:

<?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.

Rate the answer?

Total rating: 5.0

If you didn’t find the answer on your question, please, ask here:

Back to top