jehzlau
jehzlau

Reputation: 627

Show something in a subpage and all pages under that subpage in PHP

How can I display an element in a specific page and all pages under that specific page using PHP? For example I want to display something under the page example.com/blog and all the subpages of /blog, like blog/another-page/ and blog/another-page/yet-another-page, but not in the homepage of that site.

In Magento, I was able to display a specific element on a specific page using the code below:

$currentUrl = Mage::helper('core/url')->getCurrentUrl();
$url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
$path = $url->getPath();
$blogPaths = array('/blog', '/blog/', '/index.php/blog/');
if(in_array($path, $blogPaths))
{
    //Do something on /blog
}

SOURCE: Get Current URL in Magento and show something

But if I browse to /blog/another-page, that specific element that I want to show disappears. I also want to show it in all sub-pages of that sub-page.

The only method that I can think now is adding all the sub-pages in that array, but it will be very ver very long. For instance, I have 1000+ pages. That would be a very dumb move.

I have tried /blog/* but it didn't work. I'm pretty sure it's wrong. Is there a faster and easier way to check if it's a /blog page or any other page under that page, then show this blah blah blah?

I hope some Magento / PHP expert can guide me to the right path. :(

Upvotes: 0

Views: 989

Answers (1)

johnecon
johnecon

Reputation: 343

I guess you just added the '/blog/*' in the in_array function. That of course won't work. I would do the following:

function startsWith($haystack, $needle)
{
    return $needle === "" || strpos($haystack, $needle) === 0;
}

$currentUrl = Mage::helper('core/url')->getCurrentUrl();
$url = Mage::getSingleton('core/url')->parseUrl($currentUrl);
$path = $url->getPath();
if (startsWith($path, '/blog/') || (strcmp($path, '/blog') == 0))
{
    //Do something on /blog
}

Hope it helps (I got the starts with function from startsWith() and endsWith() functions in PHP)

Upvotes: 2

Related Questions