Skip to content
Advertisement

How to add a class to an “a href” element using PHP?

I am trying to add a “nav-active” class to a navigation element with PHP. Here is my code but is not adding the class. What can possibly be wrong?

Here is the bit of code I am trying to change, so my FAQ navigation item has “nav-active” class:

<li class="nav-item">
            <a class="nav-link" <?php if ($thisPage=="faq") 
echo "class=" nav-active""; ?> href="/faq">FAQ</a>
          </li>

Here is the full nav2.php code:

<!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-light fixed-top" id="mainNav">
    <div class="container">
      <a class="navbar-brand" href="/">Ukryj Się</a>
      <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
        Menu
        <i class="fas fa-bars"></i>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="/">O Projekcie</a>
          </li>
            <li class="nav-item">
            <a class="nav-link" <?php if ($thisPage=="faq") 
echo "class=" nav-active""; ?> href="/faq">FAQ</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/blog">Blog</a>
          </li>
          <li class="nav-item">
            <a class="nav-link" href="/#signup">Kontakt</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="/en/blog">🇬🇧 English</a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

EDIT: $thisPage is declared in the faq.php file:

<!DOCTYPE html>
<?php $thisPage="faq"; ?>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="Wynajmij magiczny dom w lesie z prywatnym dostępem do jeziora, sauną, kominkiem. Pozbądź się ograniczeń, zyskaj niepowtarzalną energię wprost z natury. Uwolnij się od wielkomiejskiego pędu. Pobudź swoją kreatywność.">
  <meta name="author" content="">

Advertisement

Answer

Begining of each php page:

<?php
$thisPage="faq"; //Pagename
?>

Navar.php:

<li class="nav-item">
<a href="/faq" class="nav-link <?php if($thisPage=='faq') echo 'nav-active"'; ?>">FAQ</a>
</li>
<li class="nav-item">
<a href="/contact" class="nav-link <?php if($thisPage=='contact') echo 'nav-active"'; ?>">CONTACT</a>
</li>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement