Skip to content
Advertisement

How to use strpos($_SERVER[‘REQUEST_URI’] to generate active classes from url segments

We’ve found a lot of answers for this but don’t fully understand them (or the strpos manual page) so sorry if this is already answered.


Setup:

Consider the following urls…

http://www.domain.com/whats-on/show-name/   
http://www.domain.com/whats-on/show-name/events

And how we’re applying the .active class in the following list item markup…

<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/events') === 0 ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>

Issues:

  1. What’s On gets the active class on the What’s On page but also on the Events page because /whats-on is also in the url: /whats-on/show-name/events

  2. Events never receives the active class


Question:

  1. How do we get strpos to check specific url segments so the .active class is applied on the correct page?

We’re trying to keep this short for the menu markup so hopefully there’s a way to do this on one line?

Any help or pointers in the right direction would be much appreciated.

Cheers

Ben

Advertisement

Answer

Function strpos gives you the position of a string (needle) in another string (haystack). So by doing

strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0

You are checking if the REQUEST_URI starts with “/whats-on” (is at position 0). Since both URLs start with “/whats-on”, the first item will always be active and the second never.

One fix would be to add a check for “/events”:

<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') === false ? 'active' : ''); ?>" href="<?= $ShowWhatsOn; ?>">What's on</a>
</li>
<li>
    <a class="<?= (strpos($_SERVER['REQUEST_URI'], '/whats-on') === 0 && strpos($_SERVER['REQUEST_URI'], '/events') !== false ? 'active' : ''); ?>" href="<?= $ShowEvents; ?>">Events</a>
</li>

Although this gets a bit verbose for your template, so you may want to break the logic out into a function like isActive().

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement