Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Current URL in Magento and show something

Tags:

php

magento

I'm trying to get the current URL in Magento and show something if I'm currently on that page. So far, this is what I did and it worked.

 <?php  $currentUrl = $this->helper('core/url')->getCurrentUrl();  ?>        <?php if($currentUrl === 'http://powerplantv2.jehzlau.net/blog') { ?>I am in the blog page<?php } ?> 

However, I don't want to hard code the URL in the source code, because If I transfer to another server, I need to modify the phtml file again.

I tried everything that I found online, but it didn't work. I hope some Magento expert here can enlighted me of what I'm doing wrong. :(

like image 257
jehzlau Avatar asked Aug 07 '14 21:08

jehzlau


People also ask

How can get current URL in Magento?

If you need to get current URL in Magento 2 PHTML file the easiest way to do this is to use the following code: $currentUrl = $block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]); This is the best method since you don't even need to use the Object Manager.

How do I get parameters in Magento 2?

You can get Post Data value in the After plugin using Magento 2. You can get all the Params() data after the plugin which is sent by request. If you send the query string Or data within the URL, you can get those data using getParams() in the after plugin.


2 Answers

You can retrieve the current URL path by doing the following:

$currentUrl = Mage::helper('core/url')->getCurrentUrl(); $url = Mage::getSingleton('core/url')->parseUrl($currentUrl); $path = $url->getPath(); 

Then using some basic logic, you can target the /blog page.

$blogPaths = array('/blog', '/blog/', '/index.php/blog/'); if(in_array($path, $blogPaths)) {     //Do something on /blog } 
like image 154
Axel Avatar answered Oct 07 '22 00:10

Axel


An alternate solution, would be to check the controller that's being called. Check the output of these and see if it works for ya. This works inside the template files.

 /**  * get Controller name  */ $this->getRequest()->getControllerName();  /**  * get Action name, i.e. the function inside the controller  */ $this->getRequest()->getActionName();  /**  * get Router name  */ $this->getRequest()->getRouteName();  /**  * get module name  */ $this->getRequest()->getModuleName(); 
like image 39
espradley Avatar answered Oct 06 '22 22:10

espradley