How add class='active' to html menu with php - php

I want to put my html navigation in a separate php file so when I need to edit it, I only have to edit it once. The problem starts when I want to add the class active to the active page.
I've got three pages and one common file.
common.php :
<?php
$nav = <<<EOD
<div id="nav">
<ul>
<li><a <? if($page == 'one'): ?> class="active"<? endif ?> href="index.php">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
?>
index.php :
All three pages are identical except their $page is different on each page.
<?php
$page = 'one';
require_once('common.php');
?>
<html>
<head></head>
<body>
<?php echo $nav; ?>
</body>
</html>
This simply won't work unless I put my nav on each page, but then the whole purpose of separating the nav from all pages is ruined.
Is what I want to accomplish even possible? What am I doing wrong?
Thanks
EDIT: When doing this, the php code inside the li don't seem to run, it's just being printed as if it was html

why don't you do it like this:
in the pages:
<html>
<head></head>
<body>
<?php $page = 'one'; include('navigation.php'); ?>
</body>
</html>
in the navigation.php
<div id="nav">
<ul>
<li>
<a <?php echo ($page == 'one') ? "class='active'" : ""; ?>
href="index1.php">Tab1</a>/</li>
<li>
<a <?php echo ($page == 'two') ? "class='active'" : ""; ?>
href="index2.php">Tab2</a>/</li>
<li>
<a <?php echo ($page == 'three') ? "class='active'" : ""; ?>
href="index3.php">Tab3</a>/</li>
</ul>
</div>
You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.
Later edit: fixed syntax error.

A very easy solution to this problem is to do this.
<ul>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>">Home</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'portfolio.php'){echo 'current'; }else { echo ''; } ?>">Portfolio</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'services.php'){echo 'current'; }else { echo ''; } ?>">Services</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'contact.php'){echo 'current'; }else { echo ''; } ?>">Contact</li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'links.php'){echo 'current'; }else { echo ''; } ?>">Links</li>
</ul>
Which will output
<ul>
<li class="current">Home</li>
<li class="">Portfolio</li>
<li class="">Services</li>
<li class="">Contact</li>
<li class="">Links</li>
</ul>

Your index.php code is correct. I am including the updated code for common.php below then I will explain the differences.
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = <<<EOD
<div id="nav">
<ul>
<li><a $class href="index.php">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
?>
The first issue is that you need to make sure that the end declaration for your heredoc -- EOD; -- is not indented at all. If it is indented, then you will get errors.
As for your issue with the PHP code not running within the heredoc statement, that is because you are looking at it wrong. Using a heredoc statement is not the same as closing the PHP tags. As such, you do not need to try reopening them. That will do nothing for you. The way the heredoc syntax works is that everything between the opening and closing is displayed exactly as written with the exception of variables. Those are replaced with the associated value. I removed your logic from the heredoc and used a tertiary function to determine the class to make this easier to see (though I don't believe any logical statements will work within the heredoc anyway)
To understand the heredoc syntax, it is the same as including it within double quotes ("), but without the need for escaping. So your code could also be written like this:
<?php
$class = ($page == 'one') ? 'class="active"' : '';
$nav = "<div id=\"nav\">
<ul>
<li><a $class href=\"index.php\">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>";
?>
It will do exactly the same thing, just is written somewhat differently. Another difference between heredoc and the string is that you can escape out of the string in the middle where you can't in the heredoc. Using this logic, you can produce the following code:
<?php
$nav = "<div id=\"nav\">
<ul>
<li><a ".(($page == 'one') ? 'class="active"' : '')." href=\"index.php\">Tab1</a>/</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>";
?>
Then you can include the logic directly in the string like you originally intended.
Whichever method you choose makes very little (if any) difference in the performance of the script. It mostly boils down to preference. Either way, you need to make sure you understand how each works.

I think you need to put your $page = 'one'; above the require_once.. otherwise I don't understand the question.

Why don't you create a function or class for this navigation and put there active page as a parameter? This way you'd call it as, for example:
$navigation = new Navigation( 1 );
or
$navigation = navigation( 1 );

I know this is old, but none of these answers are very good (sry ppl)
The BEST way to do it (without writing out convoluted classes) is to compare the current $_SERVER['REQUEST_URI'] to the href of the link. You're almost there.
Try this. (Taken from http://ma.tt/scripts/intellimenu/)
$nav = <<<EOD
<div id="nav">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
</ul>
</div>
EOD;
$lines = explode("\n", $nav);
foreach($lines as $line)
{
if(preg_match('/href="([^"]+)"/', $line, $url)) {
if(substr($_SERVER['REQUEST_URI'], 0, 5) == substr($url[1], 0, 5)) {
$line = str_replace('><a', ' class="current-menu-item"><a', $line);
}
}
echo $line . "\n";
}

$page='one' should occur before you require_once() not after. After is too late- the code has already been required, and $nav has already been defined.
You should use include('header.php'); and include('footer.php'); instead of setting a $nav variable early on. That increases flexibility.
Make more functions. Something like this really makes things easier to follow:
function maybe($x,$y){return $x?$y:'';}
function aclass($k){return " class=\"$k\" "; }
then you can write your "condition" like this:
<a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....

You could use this PHP, hope it helps.
<?php if(basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>
So a list would be like the below.
<ul>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'home' ) { ?> class="active" <?php } else { ?> <?php }?>><i class="fa fa-dashboard"></i> <span>Home</span></li>
<li <?php if( basename($_SERVER['PHP_SELF'], '.php') == 'listings' ) { ?> class="active" <?php } else { ?> <?php }?>><i class="fa fa-th-list"></i> <span>Other</span></li>
</ul>

CALL common.php
<style>
.ddsmoothmenu ul li{float: left; padding: 0 20px;}
.ddsmoothmenu ul li a{display: block;
padding: 40px 15px 20px 15px;
color: #4b4b4b;
font-size: 13px;
font-family: 'Open Sans', Arial, sans-serif;
text-align: right;
text-transform: uppercase;
margin-left: 1px; color: #fff; background: #000;}
.current .test{ background: #2767A3; color: #fff;}
</style>
<div class="span8 ddsmoothmenu">
<!-- // Dropdown Menu // -->
<ul id="dropdown-menu" class="fixed">
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'index.php'){echo 'current'; }else { echo ''; } ?>">Home <i>::</i> <span>welcome</span></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'about.php'){echo 'current'; }else { echo ''; } ?>">About us <i>::</i> <span>Who we are</span></li>
<li class="<?php if(basename($_SERVER['SCRIPT_NAME']) == 'course.php'){echo 'current'; }else { echo ''; } ?>">Our Courses <i>::</i> <span>What we do</span></li>
</ul><!-- end #dropdown-menu -->
</div><!-- end .span8 -->
add each page
<?php include('common.php'); ?>

<ul>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="user.php" ><span>Article</span></a></li>
<li><a <?php echo ($page == "yourfilename") ? "class='active'" : ""; ?> href="newarticle.php"><span>New Articles</span></a></li>
</ul>

The solution i'm using is as follows and allows you to set the active class per php page.
Give each of your menu items a unique class, i use .nav-x (nav-about, here).
<li class="nav-item nav-about">
<a class="nav-link" href="about.php">About</a>
</li>
At the top of each page (about.php here):
<!-- Navbar Active Class -->
<?php $activeClass = '.nav-about > a'; ?>
Elsewhere (header.php / index.php):
<style>
<?php echo $activeClass; ?> {
color: #fff !important;
}
</style>
Simply change the .nav-about > a per page, .nav-forum > a, for example.
If you want different styling (colors etc) for each nav item, just attach the inline styling to that page instead of the index / header page.

seperate your page from nav bar.
pageOne.php:
$page="one";
include("navigation.php");
navigation.php
if($page=="one"){$oneIsActive = 'class="active"';}else{ $oneIsActive=""; }
if($page=="two"){$twoIsActive = 'class="active"';}else{ $twoIsActive=""; }
if($page=="three"){$threeIsActive = 'class="active"';}else{ $threeIsActive=""; }
<ul class="nav">
<li <?php echo $oneIsActive; ?>>One</li>
<li <?php echo $twoIsActive; ?>><a href="#">Page 2</li>
<li <?php echo $threeIsActive; ?>><a href="#">Page 3</li>
</ul>
I found that I could also set the title of my pages with this method as well.
$page="one";
$title="This is page one."
include("navigation.php");
and just grab the $title var and put it in between the "title" tags. Though I am sending it to my header page above my nav bar.

<a href="store/index" <?php if($_SERVER['REQUEST_URI'] == '/store/index') { ?>class="active"<?php } ?> > Link </a>
<a href="account/referral" <?php if($_SERVER['REQUEST_URI'] == '/account/referral') { ?>class="active"<?php } ?> > Link </a>

PHP code
<?php
function activeClass($chkStr){
// echo "testing data";
// echo strlen($_SERVER['REQUEST_URI']);
if($chkStr=="home" && strlen($_SERVER['REQUEST_URI'])<3){
return "active";
}
if (stripos($_SERVER['REQUEST_URI'], $chkStr)!==false){
return "active";
}
else{
return "";
}
}
?>
HTML CODE :
<ul class="navbar-nav">
<li class="nav-item <?php echo activeClass("home"); ?>">
<a class="nav-link txt" href="/">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item <?php echo activeClass("about-us.php"); ?>">
<a class="nav-link txt" href="about-us.php">About Us</a>
</li>
<li class="nav-item <?php echo activeClass("services.php"); ?>">
<a class="nav-link txt" href="services.php">Services</a>
</li>
<li class="nav-item <?php echo activeClass("our-team.php"); ?>">
<a class="nav-link txt" href="our-team.php">Our team</a>
</li>
<li class="nav-item <?php echo activeClass("media-awards.php"); ?>">
<a class="nav-link txt" href="media-awards.php">Media & Awards</a>
</li>
<li class="nav-item <?php echo activeClass("blog.php"); ?>">
<a class="nav-link txt" href="blog.php">Blog</a>
</li>
<li class="nav-item <?php echo activeClass("contact-us.php"); ?>">
<a class="nav-link txt" href="contact-us.php">Contact Us</a>
</li>
</ul>

Related

is_page() to show current active page

I'm trying to style the active link with is_page() function. And it works for the first nav item. But when I click the "om" link it will get styling, but the styling for "hem" remains. But when I click the "blogg" and "tutorial" links none of the links gets any styling.
This is the code that I have in header.php.
<nav>
<button class="menuButton">Meny</button>
<div class="menu">
x
<ul>
<h2>Meny</h2>
<li class="<?php if (is_page("")) { echo "active-page"; } ?>">Hem</li>
<li class="<?php if (is_page("/om")) { echo "active-page"; } ?>">Om</li>
<li class="<?php if (is_page("/blogg")) { echo "active-page"; } ?>">Blogg arkiv</li>
<li class="<?php if (is_page("/tutorial")) { echo "active-page"; } ?>">Tutorials arkiv</li>
</ul>
</div>
</nav>
Is this the wrong way to use the is_page()function? I'm a little lost here. The styling that gets applied is just a simple text-decoration: underline; CSS style.
Try this
<nav>
<button class="menuButton">Meny</button>
<div class="menu">
x
<ul>
<h2>Meny</h2>
<li class="<?php if (is_page("")) { echo "active-page"; } ?>">Hem</li>
<li class="<?php if (is_page("om")) { echo "active-page"; } ?>">Om</li>
<li class="<?php if (is_page("blogg")) { echo "active-page"; } ?>">Blogg arkiv</li>
<li class="<?php if (is_page("tutorial")) { echo "active-page"; } ?>">Tutorials arkiv</li>
</ul>
</div>
</nav>

Active Navigation Bar with PHP?

I'm trying to make an active navigation bar using PHP where the current page will be highlighted or colored in the navigation bar. The code I used:
<ul class="topmenu">
<li <?php if($_GET['page']="home") { ?> class="active" <?php } ?>>
<b>Bienvenue</b>
</li>
<li <?php if($_GET['page']="livres") { ?> class="active" <?php } ?>>
<b>Livres</b>
</li>
<li <?php if($_GET['page']="bibliotheque") { ?> class="active" <?php } ?>>
<b>Bibliothèque</b>
</li>
<li <?php if($_GET['page']="universite") { ?> class="active" <?php } ?>>
<b>L'université</b>
</li>
<li <?php if($_GET['page']="contact") { ?> class="active" <?php } ?>>
<b>Contact</b>
</li>
</ul>
The code will put the attribut in the class active if the page is the current page in the navigation bar. However, all the attributs will be given the class active in this case. How do I fix this?
P.S: I am not looking for any JS or jQuery alternatives, I'm trying to make this work with PHP only.
You could use $_SERVER['SCRIPT_NAME'].
<ul class="topmenu">
<li <?php if($_SERVER['SCRIPT_NAME']=="/home.php") { ?> class="active" <?php } ?>><b>Bienvenue</b></li>
<li <?php if($_SERVER['SCRIPT_NAME']=="/livres.php") { ?> class="active" <?php } ?>><b>Livres</b></li>
<li <?php if($_SERVER['SCRIPT_NAME']=="/bibliotheque.php") { ?> class="active" <?php } ?>><b>Bibliothèque</b></li>
<li <?php if($_SERVER['SCRIPT_NAME']=="/universite.php") { ?> class="active" <?php } ?>><b>L'université</b></li>
<li <?php if($_SERVER['SCRIPT_NAME']=="/contact.php") { ?> class="active" <?php } ?>><b>Contact</b></li>
</ul>
I don't use PHP, but give the current page the active tag, and change it per file. Then a single class definition in the CSS handles changing the color for each page.
HTML:
<nav>
<a class="active" href="/home/">Home</a>
Calendar
Community
</nav>
CSS:
.active {
background-color: #4CAF50;
}
Declare page variables at the very top of each individual page.
Example: <? $page="home";?>
For each list item in your nav bar add if statment with corresponding variable and active class.
Example: <li class="<?if($page=="home"){?>active<?}?>"><b>Bienvenue</b></li>
What this does is assign each page a variable. The variable is compared in the if statements in the nav bar to determine which li gets the active class.
I'm using bootstrap 4 class. I've achieved Active Class selection something like this.
<li class="nav-item">
<a
<?php if ($_SERVER['SCRIPT_NAME'] == "/somepath/yourfile1.php") { ?>
class="nav-link active"
<?php } else { ?>
class="nav-link"
<?php } ?>
href="yourfile1.php">Home
</a>
</li>
<li class="nav-item">
<a
<?php if ($_SERVER['SCRIPT_NAME'] == "/somepath/yourfile2.php") { ?>
class="nav-link active"
<?php } else { ?>
class="nav-link"
<?php } ?>
href="yourfile2.php">Home
</a>
</li>
Repeat this logic for further li tags. Hope this helps someone else.
The code work correctly if you use "==" instead of "=" in The if construct
Еxample:
if($_GET['page'] **==** "home")...
Instead:
if($_GET['page'] **=** "home")...
Hope this helps someone else...

Add class="active" to active page using PHP

Dynamic Header, CSS Class Change To Active USING PHP (dirrectory)
I want the class of the <li> tag to change under the active dirrectory...
now, every guide shows me how to do it when your page equals it, but i want to change
the <li> depending on what dirrectory im on
for example:
if say im on http://example.com/RESOURCES/code/opensource, or http://example.com/RESOURCES/images/clipart i want the "RESOURCES" ^^ <li> to be 'class="active"' while the rest display 'class="noactive"'
or if im on http://example.com/tutorials/css/flawless-dropdown-menu I want the "tutorials" <li> to be 'class="active"' while the rest are 'class="noactive"'
URL Setup:
This is my example of how my url's are displayed...
http://example.com/tutorials/css/flawless-dropdown-menu
^^That URL is the page of a tutorial....under the "tutorials" directory, than under the "CSS" category directory, than the page title (all of these directories are not real and are rewrites from .htaccess) [irrelevant]
Navigation Setup:
<ul id="mainnav">
<li class="noactive">Home</li>
<li class="active">Tutorials</li>
<li class="noactive">Resources</li>
<li class="noactive">Library</li>
<li class="noactive">Our Projects</li>
<li class="noactive">Community</li>
</ul>
Figured out the ANSWER...I was over thinking it.
HTML
<ul id="mainnav">
<li class="<?php if ($first_part=="") {echo "active"; } else {echo "noactive";}?>">Home</li>
<li class="<?php if ($first_part=="tutorials") {echo "active"; } else {echo "noactive";}?>">Tutorials</li>
<li class="<?php if ($first_part=="resources") {echo "active"; } else {echo "noactive";}?>">Resources</li>
<li class="<?php if ($first_part=="library") {echo "active"; } else {echo "noactive";}?>">Library</li>
<li class="<?php if ($first_part=="our-projects") {echo "active"; } else {echo "noactive";}?>">Our Projects</li>
<li class="<?php if ($first_part=="community") {echo "active"; } else {echo "noactive";}?>">Community</li>
</ul>
PHP
<?php
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$first_part = $components[1];
?>
header.php
$activePage = basename($_SERVER['PHP_SELF'], ".php");
nav.php
<ul>
<li class="<?= ($activePage == 'index') ? 'active':''; ?>">Home</li>
<li class="<?= ($activePage == 'tutorials') ? 'active':''; ?>">Tutorials</li>
...
Through PHP you can try -
<?php
// gets the current URI, remove the left / and then everything after the / on the right
$directory = explode('/',ltrim($_SERVER['REQUEST_URI'],'/'));
// loop through each directory, check against the known directories, and add class
$directories = array("index", "tutorials","resources","library","our-projects","community"); // set home as 'index', but can be changed based of the home uri
foreach ($directories as $folder){
$active[$folder] = ($directory[0] == $folder)? "active":"noactive";
}
?>
<ul>
<li class="<?php echo $active['index']?>">Home</li>
<li class="<?php echo $active['tutorials']?>">Tutorials</li>
<li class="<?php echo $active['resources']?>">Resources</li>
<li class="<?php echo $active['library']?>">Library</li>
<li class="<?php echo $active['our-projects']?>">Our Projects</li>
<li class="<?php echo $active['community']?>">Community</li>
</ul>
Maybe this helps you:
$(document).ready(function()
{
var parts = document.URL.split("/");
// [http:, empty, your domain, firstfolder]
var firstFolder = parts[3];
$("#mainnav li").attr("class", "noactive");
$("#mainnav a[href='/" + firstFolder + "/']").parent().attr("class", "active");
});
It's probably easier to do with jQuery but this works:
$url='http://example.com/tutorials/css/flawless-dropdown-menu';//pass the current url here instead of a static string.
$segments = explode ("/",$url);
$menuItems=array('Tutorials','Resources', 'Library', 'Our-Projects','Community');
$menu=array();
foreach ($menuItems as $menuItem) {
if($segments[3]==strtolower($menuItem)){
$menu[]=('<li class="active">'.str_replace("-"," ",$menuItem).'</li>');
} else {
$menu[]=('<li class="no-active">'.str_replace("-"," ",$menuItem).'</li>');
}
}
foreach ($menu as $item) {
echo $item.'<br />';
}
if you use mysql_fetch defined your row for menu title.
if we take your menu title is MENU in mysql database and you have to put in
(Home,tutorials,library,resources,our-projects,community)
<?php
//connect your data bass
include(connection.php');
//get your from ID like www.google?id=1
$id = $_GET['id'];
$query = "select * from pages where id='$id'";
$query1 = mysql_query($query);
while($row= mysql_fetch_array($query1))
{
?>
<html>
<?php $active= $row['MENU'];?>
<ul>
<li class="<?php if($active=='Home'){echo 'active';}else{echo'noactive';}?>">Home</li>
<li class="<?php if($active=='tutorials'){echo 'active';}else{echo'noactive';}?>">Tutorials</li>
<li class="<?php if($active=='resources'){echo 'active';}else{echo'noactive';}?>">Resources</li>
<li class="<?php if($active=='library'){echo 'active';}else{echo'noactive';}?>">Library</li>
<li class="<?php if($active=='our-projects'){echo 'active';}else{echo'noactive';}?>">Our Projects</li>
<li class="<?php if($active=='community'){echo 'active';}else{echo'noactive';}?>">Community</li>
</ul>
</html>
<?php };?>
This answer will apply if all your pages have a php extension and you want a long messy way. I put the code below on top of every php page giving each page an ID which means all pages will have an ID which is tiresome and boring and hard to track.
<?php $page = 1; ?>
Now in my header or navigation I used the code below to put the active class. You can also put an else if you want something else.
<nav id="navbar" class="navbar">
<ul>
<li class="<?php if($page == 1){ echo "active"; } ?>"><a class="url" href="index.php">Index</a></li>
<li class="<?php if($page == 2){ echo "active"; } ?>"><a class="url" href="single-post.php">Information</a></li>
<li class="<?php if($page == 3){ echo "active"; } ?>"><a class="url" href="single-post.php">Wanted</a></li>
<li class="<?php if($page == 4){ echo "active"; } ?>"><a class="url" href="single-post.php">Workshop</a></li>
<li class="<?php if($page == 5){ echo "active"; } ?>"><a class="url" href="gallery.php">Gallery</a></li>
<li class="<?php if($page == 6){ echo "active"; } ?>"><a class="url" href="featured.php">Featured</a></li>
<li class="<?php if($page == 7){ echo "active"; } ?>"><a class="url" href="contact.php">Contact Us</a></li>
</ul>
</nav>
"includes/header.php" - This goes in Top of the File
<?php
$activePage = basename($_SERVER['PHP_SELF']);
$index="";
$nosotros="";
$cursos="";
$contacto="";
switch ($activePage) {
case 'index.php':
$index=' class="current"';
break;
case 'nosotros.php':
$nosotros=' class="current"';
break;
case 'cursos.php':
$cursos=' class="current"';
break;
case 'contacto.php':
$contacto=' class="current"';
break;
default:
break;
}
?>
and this goes on the nav section
<ul>
<?php
echo '<li'.$index.'><div>Inicio</div></li>';
echo '<li'.$nosotros.'><div>Nosotros</div></li>';
echo '<li'.$cursos.'><div>Cursos</div></li>';
echo '<li><div>Academia</div></li>';
echo '<li><div>Tienda</div></li>';
echo '<li'.$contacto.'><div>Contacto</div></li>';
?>
</ul>
Try the following:
<ul class="sub-menu">
<div class="h-10"></div>
<li class="<?php if ($your_variable=="test") {echo "active"; }
else{echo"noactive";}?>">
Test
</li>
<li class="<?php if ($your_variable=="test2") {echo "active";
} else {echo"noactive";}?>">
<a href="test2.php" >Test2</a>
</li>
<li class="<?php if ($your_variable=="test3") {echo
"active"; } else {echo "noactive";}?>">
Test3
</li>
</ul>
**strong PHP text**
<?php
$directoryURI = $_SERVER['REQUEST_URI'];
$path = parse_url($directoryURI, PHP_URL_PATH);
$components = explode('/', $path);
$your_variable = basename($_SERVER['PHP_SELF'], ".php");
?>
Here we can do a simple thing also :
<li class="page-scroll <?php if(basename($_SERVER['PHP_SELF'])=="aboutus.php"){echo "active";} ?>">About us</li>
Here is another take using PHP:
<ul class="navbar-nav">
<?php
// Defines all pages in navigation
$pages = array(
'Home' => 'index.php',
'Products' => 'products.php',
'Services' => 'services.php',
'Contact' => 'contact.php',
'About' => 'about.php'
);
// Gets active page URL
$active = basename($_SERVER['PHP_SELF']);
// Loops through all pages
foreach ($pages as $title => $url) {
// Checks if active url is matched and adds active CSS class
if ($active === $url) {
echo '<li>'.$title.'</li>';
}
// Prints out default style for remaining links
else {
echo '<li>'.$title.'</li>';
}
}
?>
</ul>
$getUrl = $_SERVER['REQUEST_URL']; -> www.example.com/home.php
$getFileName = explode('/',$getUrl);
The result of $getFileName Will Be In Array ->[" ","home.php"]
$result = $getFileName[2]; //home.php
<li class="<?php if ($result=='' || $result == 'index.php') {echo 'active'; }?>"><a href='#'>Home</a></li>
<li class="<?php if ($result=='about.php') {echo 'active'; }?>"><a href='#'>About Us</a></li>
<li class="<?php if ($result=='contact.php') {echo 'active'; }?>"><a href='#'>Contact Us</a></li>
You can use str_replace for this.
$path = $_SERVER['REQUEST_URI'];
$active = str_replace('/','', $path);
<ul>
<li class="nav-item <?php if($active == '' || $active == 'index.php'){echo 'active';}?>">
<a class="nav-link" href="index.php">HOME</a>
</li>
<li class="nav-item <?php if($active == 'about.php'){echo 'active';}?>">
<a class="nav-link" href="about.php">ABOUT US</a>
</li>
</ul>
<?php $request_uri= $_SERVER['REQUEST_URI'];?>
<ul>
<li class="<?php if((strpos($request_uri,"index.html")!==false) || $request_uri=="" || $request_uri=="/"){echo "selected";}?>">Home</li>
<li class="<?php if((strpos($request_uri,"service")!==false)){echo "selected";}?>">Services </li>
<li class="<?php if((strpos($request_uri,"product")!==false)){echo "selected";}?>">Products</li>
<li class="<?php if((strpos($request_uri,"blog")!==false)){echo "selected";}?>">Blog</li>
<li class="<?php if((strpos($request_uri,"question")!==false)){echo "selected";}?>">Ques & Ans</li>
<li class="<?php if((strpos($request_uri,"career")!==false)){echo "selected";}?>">Career</li>
<li class="<?php if((strpos($request_uri,"about-us")!==false)){echo "selected";}?>">About</li>
</ul>

add active class to menu links using php

<div class="menu clearfix">
<ul>
<li>start</li>
<li>rating</li>
<li>upload</li>
</ul>
Was a while since i used php. Is there any smart way to do a foreach in php and render this menu + an "active" class to the clicked link. So if the active page is "rating", the html would render:
<div class="menu clearfix">
<ul>
<li>start</li>
<li>rating</li>
<li>upload</li>
</ul>
Thanks
Assuming the $_GET value of p would be rating (or any other link in the menu for that matter), one could do something like this:
<?php
echo "<div class=\"menu clearfix\">";
echo "<ul>";
$links = array('rating', 'upload', 'about');
foreach ($links as $link) {
$active = "";
if (!empty($_GET['p']) && $link == $_GET['p']){
$active = 'class="active"';
}
echo "<li><a href=\"./?p=$link\" $active>$link</a></li>";
}
echo "</ul></div>"
?>
As far as I understand you want to know which li is active after request.
If it is - you have to get $_GET parameter smth like $_GET['p'].
And do rendering, smth like:
foreach($ul as $li)
{
if ($_GET['p'] == $li->code)
echo 'class="active"';
}
For example:
<div class="menu clearfix">
<ul>
<?php foreach($ul as $li): ?>
<li><a href="<?php echo $li->url;?>" <?php echo $_GET['p']==$li->get ? class="active" : ''?>><?php echo $li->name;?></a></li>
<?php endforeach; ?>
</ul>
<ul class="sub-nav" >
<?php
$full_name = $_SERVER['PHP_SELF'];
$name_array = explode('/',$full_name);
$count = count($name_array);
$page_name = $name_array[$count-1];
?>
<li><a class="<?php echo ($page_name=='where-to-buy.php')?'active':'';?>" href="where-to-buy.php">WHERE TO BUY</a></li>
<li><a class="<?php echo ($page_name=='about.php')?'active':'';?>" href="about.php">ABOUT US</a></li>
<li><a class="<?php echo ($page_name=='contact.php')?'active':'';?>" href="contact.php">CONTACT US</a></li>
Please follow below URL to live demo...
https://webdesignerhut.com/active-class-navigation-menu/

Create a php menu that highlights current tab

So I have a menu in a php file that looks like this (This is the whole file. I'm totally new to PHP.)
menu.php:
<li id="current"><span>Home</span></li>
<li><span>Blog</span></li>
<li><span>Results</span></li>
<li><span>Pictures</span></li>
<li><span>Our Location</span></li>
Now in my pages I do this (index.php):
<div id="tabs1" >
<ul>
<!-- CSS Tabs -->
<?php include("menu.php"); ?>
</ul>
</div>
So what I want to be able to do is change the line above to this:
<?php include("menu.php?current=pictures"); ?>
Which would make the active tab the Pictures tab. How can I do this?
You could also try this:
Your php script
<?php
$selected = "pictures";
$current_id = ' id="current"';
include "menu.php";
?>
this is your menu:
<ul>
<li <?php if ($selected == "pictures") print $current_id; ?>><span>Home</span></li>
<li <?php if ($selected == "blog") print $current_id; ?>><span>Blog</span></li>
<li <?php if ($selected == "home") print $current_id; ?>><span>Results</span></li>
<li <?php if ($selected == "me") print $current_id; ?>><span>Pictures</span></li>
<li <?php if ($selected == "contacts") print $current_id; ?>><span>Our Location</span></li>
</ul>
Try this:
<li <?php if($_GET['current'] == 'home') {echo 'id="current"'}?>><span>Home</span></li>
<li <?php if($_GET['current'] == 'blog') {echo 'id="current"'}?>><span>Blog</span></li>
<li <?php if($_GET['current'] == 'results') {echo 'id="current"'}?>><span>Results</span></li></li>
and so on....
worth looking at
intelligent navigation
<nav>
<style>
#active{
color:#FFC801;
}
</style>
<?php
$activePage = basename($_SERVER['PHP_SELF'], ".php");
?>
<ul>
<li>About Us</li>
<li>Mentors</li>
<li>Tours</li>
<li>Animation</li>
<li>Blog</li>
<li>Testimonials</li>
<li>Press/Media</li>
<li>Facts</li>
</ul>
</nav>
I don't think its necessary for it to be done at the server side (using up CPU cycles).
Use javascript/CSS to achieve this.

Categories