0

I am facing issue to get current page URL when cache is enabled

<?php
     $urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
     $CurrentUrl = $urlInterface->getCurrentUrl();
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $request = $objectManager->get('Magento\Framework\App\Action\Context')->getRequest();
     echo $request->getFullActionName();
     // echo "<pre>";
     // echo $this->getBaseUrl();
     // echo strcmp($CurrentUrl, $this->getBaseUrl());
     echo $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
?>

On switching from menu to top links the current URL is not received properly. If I clear cache then I am getting the desired result.

1 Answer 1

1

Not sure this is the problem, but since you say it's cache related, it could be the fact that the top links block is cached and the cache does not take into account the current url.
So if you don't have a cache for it, and the first page you visit is the homepage it will always create the cache containing the homepage url.
You can go around this by adding the current url to the cache key of the block.

You can do this via a plugin.
the top links block is an instance of Magento\Customer\Block\Account\Navigation as stated in Magento_Theme::view/frontend/layout/default.xml.

So let's create a plugin for that class:

Add this to frontend/di.xml in one of your modules.

<type name="Magento\Customer\Block\Account\Navigation">
    <plugin name="add-current-url-to-cache-key" type="[Vendor]\[Module]\Plugin\TopLinksPlugin" />
</type>

then create the class [Vendor]\[Module]\Plugin\TopLinksPlugin

namespace [Vendor]\[Module]\Plugin;

class TopLinksPlugin
{
    public function afterGetCacheKeyInfo(\Magento\Customer\Block\Account\Navigation $subject, array $cacheKey) 
    {
        $cacheKey[] = $subject->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
        return $cacheKey;
     }
}

This will most probably solve your issue, but it comes with a cost.
This means that you will get a different version of the cache for the top links block for each page you have.
An alternative solution would be to create a separate block that you put in the layout near the top links (or where ever you want) and have just that block cached with a cache key that is different from page to page.

Or better yet, display this url via Javascript because you can use it anywhere via window.location no matter if the page is cached or not.
I don't know what are your exact requirements for this, so I offered multiple solutions.
Just watch out for typos in the first solution. I didn't test the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.