Hello I would like to know how to use PHP in my header so that my class active can be activated when it is on the correct page.
for instance on my index.php
i have this at the top
<?php
$page = 'Home';
include("header.php");
?>
then this is in my navigation
<nav>
<ul>
<li><a class="active" href="index">Home</a></li>
<li class="rightside">Projects</li>
<li class="rightside">About</li>
<li class="rightside">Blog
<li class="rightside">Contact
</ul>
</nav>
I want the class to be activated when i am on the appropriate page if that makes any sense. Thank you, my PhP knowledge is minimal.
This is a shorthand if statement that can be used inline
<?php echo ($page == 'Home' ? 'active':'');?>
See Below
<nav>
<ul>
<li><a class="<?php echo ($page == 'Home' ? 'active':'');?>" href="index">Home</a></li>
<li class="rightside"><a class="<?php echo ($page == 'Projects' ? 'active':'');?>" href="projects">Projects</a></li>
<li class="rightside"><a class="<?php echo ($page == 'About_us' ? 'active':'');?>" href="about_us">About</a></li>
<li class="rightside"><a class="<?php echo ($page == 'Blog' ? 'active':'');?>" href="blog">Blog</a>
<li class="rightside"><a class="<?php echo ($page == 'Contact' ? 'active':'');?>" href="contact">Contact</a>
</ul>
</nav>
I personally use a jquery function for this, it saves having to declare the page type each time
jQuery
$(function () {
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('[href$="'+url+'"]').parent().addClass("active");
});
If you always declare $page before the header include, than you can use an if statement.
Just an example:
<nav>
<ul>
<li><a class="<?php echo ($page == 'Home') ? 'active' : 'rightside'; ?>" href="index">Home</a></li>
<!-- same for your other list elements -->
</ul>
</nav>
I am trying to learn PHP for a website that I am building. In CSS, I have a class, nav a.thispage, setup to make a 'button' on the navigation be the same color as the highlight. It works beautifully. But, as I added pages, I find that I needed to constantly update all of the HTML files of the site, over, and over again. I found out that PHP could help me to automate this. I use the following PHP, in my HTML to do this:
<?php include 'content/header.php';?>
The header.php file has the following content:
<header>
<h1><img id="headerimage" src="Images/GrandLodge.png"/>Lodge</h1>
<nav>
<ul>
<li>Home</li>
<li>Events</li>
<li>Social</li>
<li>About</li>
<li>Contact</li>
<li>Area Game Stores</li>
<li>PFS</li>
</ul>
</nav>
</header>
Now, because I am using this method, I can't just set the class="thispage" on the a tag. Is there a way to set the class, dynamically, with PHP? If so, how to I tell if the page loading the html is actually the page that needs it? Is using PHP even the correct way to handle this, or should I be using JavaScript?
I know this is a lot, and I didn't really provide a lot of what I have done, but I can't actually seem to see what I need to do for this. All I really need is a point in the right direction, rather than a full code sample.
Thank you for any help you can provide.
Use basename($_SERVER['REQUEST_URI'])
<header>
<h1><img id="headerimage" src="Images/GrandLodge.png"/>Lodge</h1>
<nav>
<ul>
<?php $basename = basename($_SERVER['REQUEST_URI']);?>
$class = $basename === 'index.php' || empty($basename) ? ' class="thispage"' : '';
<li <?php if($basename=="index.php" || $basename==""){?> class="thispage" <?php } ?>>Home</li>
<li <?php if($basename=="events.php"){?> class="thispage" <?php } ?>>Events</li>
<li <?php if($basename=="social.php"){?> class="thispage" <?php } ?>>Social</li>
<li <?php if($basename=="about.php"){?> class="thispage" <?php } ?>>About</li>
<li <?php if($basename=="contact.php"){?> class="thispage" <?php } ?>>Contact</li>
<li <?php if($basename=="gamestores.php"){?> class="thispage" <?php } ?>>Area Game Stores</li>
<li>PFS</li>
</ul>
</nav>
</header>
Updated another Simple way
<header>
<h1><img id="headerimage" src="Images/GrandLodge.png"/>Lodge</h1>
<nav>
<ul>
<?php $basename = basename($_SERVER['REQUEST_URI']);?>
$class = $basename === 'index.php' || empty($basename) ? ' class="thispage"' : '';
<li <?= $class ?>>Home</li>
<li <?= $class ?>>Events</li>
<li <?= $class ?>>Social</li>
<li <?= $class ?>>About</li>
<li <?= $class ?>>Contact</li>
<li <<?= $class ?>>Area Game Stores</li>
<li>PFS</li>
</ul>
</nav>
</header
You can use a bit oF PHP and JavaScript to handle this
<header>
<h1><img id="headerimage" src="Images/GrandLodge.png"/>Lodge</h1>
<nav>
<ul>
<li><a id="aHome" href="index.php">Home</a></li>
<li><a id="aEvents" href="events.php">Events</a></li>
<li><a id="aSocial" href="social.php">Social</a></li>
<li><a id="aAbout" href="about.php">About</a></li>
<li><a id="aContact" href="contact.php">Contact</a></li>
<li><a id="aGame" href="gamestores.php">Area Game Stores</a></li>
<li><a id="aPFS" href="http://someaddress" target="_blank">PFS</a></li>
</ul>
</nav>
</header>
Now suppose the visitor has landed on the About page. The code to check that and set the class name on the a tag would be
<?php
if ($_SERVER['SCRIPT_NAME'] == '/about.php') {
?>
<script type="text/javascript">
document.getElementById("aAbout").className = 'thispage';
</script>
<?php
}
?>
Try it and let me know.
In order for PHP to help you, you'd have to generate your navigation within a loop. Something along the lines of:
<?php
$menu = array(
'Home' => 'index.php',
'Events' => 'events.php',
'Social' => 'social.php',
'About' => 'about.php'
);
?>
<?php foreach ($menu as $name => $href) : ?>
<?php $class_name = basename(__FILE__) === $href ? 'thispage' : ''; ?>
<li><?php echo $name; ?></li>
<?php endforeach; ?>
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>
<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/
looking for some help:)
http://69.65.3.168/~doubleop/pro.sperity/blog
is the site i am working on, you can see the navigation is a drop down. I want the green to hover over active pages.
This is a drop down menu, so i created parent pages as the main nav links, and the drop down contains child pages.
All the links are hard coded at the moment, not using wordpress' built in function.
This is my code for the active links, which works well on normal .php sites, but not on wordpress
<ul id="menu">
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'index') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?>>Home
<!--No drop downs-->
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'blog') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Blog
<!--No drop downs-->
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'business-model') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Business Model
<ul>
<li>Introduction</li>
<li>Investment Strategy</li>
<li>Investor Benefits</li>
<li>Investment Programs</li>
<li>Prosperity Partnership</li>
<li>RRSP Investment</li>
<li>Limited Partnership</li>
<li>Refferal Program</li>
<li>FAQ</li>
</ul>
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'track-record') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Tack Record
<ul>
<li>Company Overview</li>
<li>Investment Portfolio</li>
<li>Why Prosperity</li>
<li>Testimonials</li>
</ul>
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'current-oppertunities') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Current Oppertunities
<ul>
<li>Current Offerings</li>
<li>Investor Interest Form</li>
<li>Properties for Rent</li>
</ul>
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'upcoming-events') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Upcoming Events & News
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'mentorship-program') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >Mentorship Program
</li>
<li <?php $string = basename($_SERVER['SCRIPT_FILENAME']); if ( strpos($string, 'about-us') !== false ){ echo "class='active'"; }else{ echo "class='nactive'"; } ?> >About us
<ul>
<li>Mission Statement</li>
<li>Management Team</li>
<li>Contact</li>
</ul>
</ul>
(the code is showing up wierdly, but you get the idea)
I tried echoing out the script_filename, and it was index.php on every page.
Anyone know how i can go about doing this? I need the active state to stay there when the user is on the relevant page, or any relevant child pages within under the parent
Thank you
$_SERVER['SCRIPT_FILENAME'] is the same on every page since Wordpress directs all pages to the same script for processing.
If you want to search the URI for a specific string, try using $_SERVER['REQUEST_URI'] instead; that returns the requested URI, regardless of which script is being executed.
Also, in the code supplied, you misspelled "inactive" as "nactive."