29

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. :(

jehzlau
  • 627
  • 2
  • 9
  • 20
  • Anyway, I was able to solve my own problem using substr. I noticed that the blogUrl has a / in the end, so I removed it using substr, thus this code will now work to show something on a specific page instantly. :D `code` helper('core/url')->getCurrentUrl(); $blogUrl = $this->getUrl('blog'); $blogfixedurl = substr($blogUrl, 0, -1); ?> You are currently in a blog page `code` But if anyone has a better solution, you're welcome to answer. I think my code can be shorten. :D – jehzlau Aug 07 '14 at 21:17

3 Answers3

75

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
}
Axel
  • 10,732
  • 2
  • 30
  • 43
  • Oh niceee.. thanks for this. Never thought of using an array. I just trimmed it down, but will use this tip so that it will still work even url rewrites are off. Thanks Axel. :D – jehzlau Aug 07 '14 at 23:41
5

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();
espradley
  • 2,138
  • 2
  • 17
  • 15
5
$currentUrl = Mage::helper('core/url')->getCurrentUrl();
Pankaj Upadhyay
  • 2,114
  • 21
  • 22
  • 2
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, as this reduces the readability of both the code and the explanations! – Blue Aug 08 '16 at 07:10