0

I want to add a class=active to the current page im on with php

class_navigation.php

$menu = array(
  'home'  => array('text'=>'Home',  'url'=>'?p=home'),
  'away'  => array('text'=>'About',  'url'=>'?p=about'),
  'about' => array('text'=>'Contact', 'url'=>'?p=contact'),
);

class class_navigation {
  public static function GenerateMenu($items) {
    $html = "<nav>\n";

foreach($items as $item) {
      $class ="";
      if ($page == $item) {
          $class = "class='active'";
       }
      $html .= "<a href='{$item['url']}' ".$class.">{$item['text']}
      </a>\n";
    }
    $html .= "</nav>\n";
    return $html;
  }
};

nav.php

<?php 
    echo class_navigation::GenerateMenu($menu); 
?>

index.php

require_once('class/class_navigation.php');
require_once('includes/head.php');
require_once('includes/nav.php');

switch($_GET['p']){
         case "home":
              $page = 'home';
              include_once('pages/home.php');
              break 1;
         case "about":
              $page = "about";
              include_once('pages/about.php');
              break 1;
         case "contact":
              $page = "contact";
              include_once('pages/contact.php');
              break 1;    
    }

require_once('includes/footer.php');
3
  • you want this $html .= "<a href='{$item['url']}' ".$class.">{$item['text']} </a>\n"; ? where $class = 'class="active"'; Commented Oct 27, 2015 at 9:52
  • Ya but what how can I do the if statement? Commented Oct 27, 2015 at 9:54
  • check this stackoverflow.com/a/33364700/4323504 Commented Oct 27, 2015 at 9:56

1 Answer 1

2

Remove $page in switch and modify your class to this.

  • Now GenerateMenu gets current page with $page = $_GET['p'];
  • Compares it to url value in your array.
  • parse_str(substr($item['url'], 1)); parses this url and you will get $p equaling to home, if url is '?p=home' etc.

<?php
class class_navigation {
    public static function GenerateMenu($items) {
        $html = "<nav>\n";
        $page = isset($_GET['p']) ? $_GET['p'] : '';

        foreach($items as $item) {
            $class = "";

            parse_str(substr($item['url'], 1));

            if ($page == $p) {
                $class = " class='active'";
            }

            $html .= "<a href='{$item['url']}'".$class.">{$item['text']}</a>\n";
        }

        $html .= "</nav>\n";
        return $html;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.