Set active state on navigation dynamically - php

I seem to run into this problem frequently and can never find a solution. I have a Wordpress site with a top navigation. Since this is in my header.php, and used on all pages, I cannot hardcode my active menu state for each page.
How can I dynamically set the activate state to work for each page?
Here is my current nav code:
<nav id="main-menu" class="padbot">
<ul id="ce">
<li class="cemenu">About</li>
<li class="cemenu">Consulting</li>
<li class="cemenu">Intelligence</li>
<li class="cemenu">Academy</li>
<li class="cemenu">Blog</li>
<li class="cemenu">Contact</li>
</ul>
I've already setup a CSS class called "active" that has my active state properties. Ideally, what I'm looking for is when your on the "About" page (or any of the other pages), the class I created for the active state will be appended to the current li classes's.
Example:
<li class="cemenu active">About</li>
Thanks!

you could try something along the lines of
<li class="cemenu<?php echo ($_SERVER['PHP_SELF'] == '/about' ? ' active' : '');?>">About</li>

You can do this way:
This will add the active class to the <a> which contains the page from the url.
$(function(){
var url = window.location.href;
var page = url.substr(url.lastIndexOf('/')+1);
$('.cemenu a[href*="'+page+'"]').addClass('active');
});
and if you want to add class to its parent li the replace the last line to this and css class should be like this:
.active a{
css
properties
for active li's a
}
// using closest
$('.cemenu a[href*="'+page+'"]').closest('li').addClass('active');
or
// using parent
$('.cemenu a[href*="'+page+'"]').parent('li').addClass('active');
just tryout the fiddle here

First, there is a css pseudo class prepared for styling 'active' links :
a:active {css}
For your situation, you would have to add this class to your styling :
.active a, a:active {css}
But your needs seems more on the PHP side than the CSS, perhaps someone else will help you with that part. There would be a javascript solution with jQuery, finding the actual location then inject a css selector to the proper element.
Check this article and this other one about wordpress. It will help you.
Stack Overflow references :
How do I target each menu different items on active state in Wordpress
How to add Active states and icons in wordpress wp_nav_menu()
Loosing Nav Active State in Wordpress Dynamic Menu
google search

try something like this:
<?php $pages = array('about' => 'About Us', 'blog' => 'blog') ?>
<ul>
<?php foreach($pages as $url => $page): ?>
<?php $isActive = $_SERVER["REQUEST_URI"] == $url ?>
<li<?php echo $isActive ? ' class="active"' : '' ?>>
<?php echo $page ?>
</li>
<?php endforeach ?>
</ul>
It may be worth looking into using wordpres functions such as get_page_link which would be nicer than using the Server super global as that's not nice. This would also fail if you have wordpress in a folder and not the document root, it's just a simple example to get you started :)

You can try like this
<li class="<?php
if($this_page=='Home'){
echo 'active';
}
?>">
Home
</li>
<li class="<?php
if($this_page=='Contact'){
echo 'active';
}
?>">
Contact
</li>
And then in your home page
$this_page='Home';
And in your contact page
$this_page='Contact';

You could use preg_replace() to add class="active" like this:
ob_start();
echo '<ul>
<li>Page 1</li>
<li>Page 2</li>
</ul>';
$output = ob_get_clean();
$pattern = '~<li><a href="'.$url.'">~';
$replacement = '<li class="active"><a href="'.$url.'">';
echo preg_replace($pattern, $replacement, $output);

Related

How to know which screen is active if I use templates with PHP

I am using a template where the menu of my website goes, however I want to add the bootstrap active class to it so that the user knows which page he is on. At the moment the way I do it is the following:
Note that the "templates" file has several functions with an echo to display the html. Outside of the function that displays the HTML I call this option that PHP gives us.
$activePage = basename($_SERVER['PHP_SELF'], ".php");
Then I create a function to show the menu that looks like this, clearly it has more options, but to avoid putting so much code I only show this one.
function MostrarMenu(){
echo
'
<li class="nav-item">
<a class="nav-link <?= ($activePage == about) active ?>" href="about.php">Sobre nosotros</a>
</li>
';
Then in the view I call this function so that it shows the menu
<?php MostrarMenu(); ?>
$activePage = $_SERVER['REQUEST_URI'];
function MostrarMenu(){
$Active = ($activePage == '/about') ? "active": "";
echo
'
<li class="nav-item">
<a class="nav-link '.$Active.'" href="about.php">Sobre nosotros</a>
</li>
';
}

Update Header link class on page change php

I am trying to make a dynamic header in which header link classes update automatically when the page changes. so, like if the user in on index then HOME on header shows in red and if he is on folio page then folio shows in red and so on.
my code.
<?php
switch(basename($_SERVER['PHP_SELF'])){
case "index.php":
$index_hover = "act-link";
break;
case "portfolio.php":
$folio_hover = "act-link";
break;
}
?>
<style>
.act-link {color: red}
</style>
<div class="nav-holder">
Home
Folio
</div>
This code works as expected but the issues say I have 30 links in the header then it's not handy. so I want to make it dynamic so that it detects the page and update as per the need.
Thanks
From your question i think you want to add custom class in navigation menu associated with page
You can do it using php and javascript as well
Using PHP
<?php
function addActiveClass($page){
$url_array = explode('/', $_SERVER['REQUEST_URI']) ;
$url = end($url_array);
if($page == $url){
echo 'act-link'; //class name in css
}
}
?>
<ul>
<li><a class="<?php addActiveClass('home.php');?>" href="http://localhost/Home.php">Home</a></li>
<li><a class="<?php addActiveClass('aboutus.php');?>" href="http://localhost/aboutus.php">About us</a></li>
<li><a class="<?php addActiveClass('contactus.php');?>" href="http://localhost/contactus.php">Contact us</a></li>
</ul>
Here i have added function on every anchor tag addActiveClass which adds class 'act-link' depending on argument passed
Using javascript(jquery)
$(document).ready(function() {
var pathname = window.location.pathname;
$('ul > li > a[href="'+pathname+'"]').parent().addClass('act-link');
})
<ul class="nav">
<li>Home</li>
<li>About us</li>
<li>Contact us</li>
</ul>
I have used jquery here if you want you can write code is core js as well
let me know if there is confusion

how to add class 'active' on menu anchor when the menu is included wih php

My situation:
I have several pages like home.php, about.php, gallery.php ...
In all these pages i include the menu with the anchors with php. so the menu is not in the pages. In all the pages i have the line: include('includes/menu.php');
What i want to achieve: if url is mydomain.com /gallery.php the anchor in the menu should have an extra class like "active" so i can style it different (current page is open).
I tried it with jquery:
I gave all the anchors a class "clickable" like below:
<ul class="main-menu">
<li><a class="clickable" href="index.php">Home</a></li>
<li><a class="clickable" href="gallery.php">Gallery</a></li>
<li><a class="clickable" href="openingtimes.php">Openingtimes</a></li>
</ul>
And load this jquery code:
$(document).ready(function()
{
$(function() { //run when the DOM is ready
$(".clickable").click(function() {
$(this).addClass("active"); //add the class to the clicked element
});
});
});
But the problem that appears: when click on the anchor, lets say gallery.php, it gets the class "active' shortly but the gallery.php is loading and the menu is again included via php. Ofcourse, this works only if you stay on the same page.
What can i do best with this situation to make an anchor active when the specific page is loaded?
Maybe read the url and then on basis of this url add a class to the anchor?
Use $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI']
Try using:
<ul class="main-menu">
<li><a class="clickable <?php if($_SERVER['PHP_SELF'] == '/index.php') { echo "active"; } ?>" href="index.php">Home</a></li>
<li><a class="clickable <?php if($_SERVER['PHP_SELF'] == '/gallery.php') { echo "active"; } ?>" href="gallery.php">Gallery</a></li>
<li><a class="clickable <?php if($_SERVER['PHP_SELF'] == '/openingtimes.php') { echo "active"; } ?>" href="openingtimes.php">Openingtimes</a></li>
</ul>
Also make sure if the file is in another directory to add the name ex. if($_SERVER['PHP_SELF'] == '/folder/index.php')
Documentation: http://php.net/manual/en/reserved.variables.server.php

How to set current page "active" in php

Hi I have a menu on my site on each page, I want to put it in it's own menu.php file but i'm not sure how to set the class="active" for whatever page i'm on.
Here is my code: please help me
menu.php:
<li class=" has-sub">
<a class="" href="javascript:;"><i class=" icon-time"></i> Zeiten<span class="arrow"></span></a>
<ul class="sub">
<li><a class="" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="" href="sauna.php">Sauna</a></li>
<li><a class="" href="frauensauna.php">Frauensauna</a></li>
<li class=""><a class="" href="custom.php">Beauty Lounge</a></li>
<li><a class="" href="feiertage.php">Feiertage</a></li>
</ul>
</li>
this method gets the current page using php which will pass a word in this case active and places it inside the class parameter to set the page active.
<?php
function active($currect_page){
$url_array = explode('/', $_SERVER['REQUEST_URI']) ;
$url = end($url_array);
if($currect_page == $url){
echo 'active'; //class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1.php');?>" href="http://localhost/page1.php">page1</a></li>
<li><a class="<?php active('page2.php');?>" href="http://localhost/page2.php">page2</a></li>
<li><a class="<?php active('page3.php');?>" href="http://localhost/page3.php">page3</a></li>
<li><a class="<?php active('page4.php');?>" href="http://localhost/page4.php">page4</a></li>
</ul>
It would be easier if you would build an array of pages in your script and passed it to the view file along with the currently active page:
//index.php or controller
$pages = array();
$pages["offnungszeiten.php"] = "Öffnungszeiten";
$pages["sauna.php"] = "Sauna";
$pages["frauensauna.php"] = "Frauensauna";
$pages["custom.php"] = "Beauty Lounge";
$pages["feiertage.php"] = "Feiertage";
$activePage = "offnungszeiten.php";
//menu.php
<?php foreach($pages as $url=>$title):?>
<li>
<a <?php if($url === $activePage):?>class="active"<?php endif;?> href="<?php echo $url;?>">
<?php echo $title;?>
</a>
</li>
<?php endforeach;?>
With a templating engine like Smarty your menu.php would look even nicer:
//menu.php
{foreach $pages as $url=>$title}
<li>
<a {if $url === $activePage}class="active"{/if} href="{$url}">
{$title}
</a>
</li>
{/foreach}
Create a variable in each of your php file like :
$activePage = "sauna"; (different for each page)
then check that variable in your html page like this
<?php if ($activePage =="sauna") {?>
class="active" <?php } ?>
Put all the below code in menu.php and everything will be taken care of.
// function to get the current page name
function PageName() {
return substr($_SERVER["SCRIPT_NAME"],strrpos($_SERVER["SCRIPT_NAME"],"/")+1);
}
$current_page = PageName();
Use the above to get the current page name then put this in your menu
<li><a class="<?php echo $current_page == 'offnungszeiten.php' ? 'active':NULL ?>" href="offnungszeiten.php">Öffnungszeiten</a></li>
<li><a class="<?php echo $current_page == 'sauna.php' ? 'active':NULL ?>" href="sauna.php">Sauna</a></li>
<li><a class="<?php echo $current_page == 'frauensauna.php' ? 'active':NULL ?>" href="frauensauna.php">Frauensauna</a></li>
<li><a class="<?php echo $current_page == 'custom.php' ? 'active':NULL ?>" href="custom.php">Beauty Lounge</a></li>
<li><a class="<?php echo $current_page == 'feiertage.php' ? 'active':NULL ?>" href="feiertage.php">Feiertage</a></li>
where active is the name of the class which will highlight your menu item
there is two things you can do.
first you can read the current filename of the php file you request by using $_SERVER['PHP_SELF'] or $_SERVER['REQUEST_URI'] or any other $_SERVER global variables that you can use to read your current page and compare it with the link's url, something like this
<a href="offnungszeiten.php" <?php if($_SERVER['PHP_SELF']=='offnungszeiten.php'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
the second one is to create a variable that you can read globally that would store the current name of the current page, like this
<?php
$cur_page ="offnungszeiten"
?>
<a href="offnungszeiten.php" <?php if($cur_page=='offnungszeiten'){ ?>class="activatepage" <?php } ?> >
Öffnungszeiten
</a>
I have done it with php in this way,
function createTopNav($active)
{
$pages = array(
array(
'name'=>'Home',
'link'=>'index'
),
array(
'name'=>'Smartphone',
'link'=>'smartphone'
),
array(
'name'=>'Tablet',
'link'=>'tablet'
),
array(
'name'=>'About Us',
'link'=>'about'
),
array(
'name'=>'Contact Us',
'link'=>'contact'
)
);
$res = "<ul>";
$activePage = "";
foreach($pages as $key=>$val)
{
if($val['link']==$active)
{
$res.= "<li><a href='".$val['link']."' class='active' >".$val['name']."</a></li>";
}
else
{
$res.= "<li><a href='".$val['link']."'>".$val['name']."</a></li>";
}
}
$res.="</ul>";
return $res;
}
And then to call this function
echo createTopNav("about");
and the output will be like this
<ul>
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
I solved this using jQuery/javascript by running the code below each time my any page is loaded:
$(document).ready(function () {
//Get CurrentUrl variable by combining origin with pathname, this ensures that any url appendings (e.g. ?RecordId=100) are removed from the URL
var CurrentUrl = window.location.origin+window.location.pathname;
//Check which menu item is 'active' and adjust apply 'active' class so the item gets highlighted in the menu
//Loop over each <a> element of the NavMenu container
$('#NavMenu a').each(function(Key,Value)
{
//Check if the current url
if(Value['href'] === CurrentUrl)
{
//We have a match, add the 'active' class to the parent item (li element).
$(Value).parent().addClass('active');
}
});
});
This implementation assumes your menu has the 'NavMenu' ID, and uses http://hostname/scriptname.php href attributes like so:
<ul id="NavMenu">
<li>Home</li>
<li>Smartphone</li>
<li>Tablet</li>
<li>About Us</li>
<li>Contact Us</li>
</ul>
Read the javascript comments to see what's going on. If you prefer to use a different href layout (like in your original example), you have to play with the CurrentUrl variable a bit to get it to use the same layout as your href attributes.
For me this was the easiest solution since I had an existing sites with a big menu and many pages, and wanted to avoid having to modify all pages. This allows me to throw in a piece javascript code in the header file (which was a central file already) which solves the problem for all existing pages.
A bit late on the ball, but I just had to solve this myself and ended up using this Javascript method, with a small modification. This has the advantage on not requiring many changes to the current code, just run the script and voila.
window.onload = activateCurrentLink;
function activateCurrentLink(){
var a = document.getElementsByTagName("A");
for(var i=0;i<a.length;i++)
if(a[i].href == window.location.href.split("#")[0])
a[i].className = 'activelink';
}
Send page name in query string and check it on every page by getting the variable.
Simplere solution:
Borrowing the code from asprin above;
Create a new file menu.php where you will store the one and only copy of the menu. In this file, you will create a function addMenu($pageName) that take a parameter as the page name and returns a string consisting of the menu after having added the current tag.
In your HTML code, you would include(menu.php) and then call the function addMenu with the current page name. So your code will look like this:
menu.php
<?php
function addMenu($pageName){
$menu =
'<ul>
<li><a href="Öffnungszeiten.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Öffnungszeiten</span></a></li>
<li><a href="sauna.php"' . ($pageName == "Öffnungszeiten" ? "class=\"current\"" : "") . '><span>Sauna</span></a></li>
<li><a href="frauensauna.php"' . ($pageName == "Frauensauna" ? "class=\"current\"" : "") . '><span>Frauensauna</span></a></li>
<li><a href="custom.php" ' . ($pageName == "lounge" ? "class=\"current\"" : "") . '><span>Beauty Lounge</span></a></li>
<li><a href="Feiertage.php"' . ($pageName == "feiertage" ? "class=\"current\"" : "") . '><span>Feiertage</span></a></li>
</ul>';
return $menu;
}
?>
And in your HTML, say this:
<div id="menu">
<?php
include('menu.php');
echo addMenu("index");
echo $hello;
?>
</div>
This worked for me:
function active_page($script){
$actual = basename($_SERVER['PHP_SELF']);
if($script == $actual){
return 'active-page'; //class name in css
}
}
I have some simple example, see below:
<?php
function active($currect_page) {
$url = $_SERVER['REQUEST_URI'];
if($currect_page == $url){
echo 'active';
}
}
?>
<ul class="navbar-nav mr-auto">
<li class="nav-item <?php active('/');?>">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item <?php active('/other');?>">
<a class="nav-link" href="/other">Other page</a>
</li>
</ul>
Better late than never - I like to keep it simple, to be honest, especially if there's a ton of scripting and PHP going on.
I place this code on the top of each page to identify the page:
<?php
$current_page = 'home';
include 'header.php';
?>
Then your menu/navigation (mine is bootstrap 4) looks like this:
<ul class="navbar-nav mx-auto">
<li class="nav-item <?php if ($current_page=="home") {echo "active"; }?>">
<a class="nav-link" href="<?php echo SITEURL;?>/">Home</a>
</li>
<li class="nav-item <?php if ($current_page=="about") {echo "active"; }?>">
About
</li>
<li class="nav-item <?php if ($current_page=="store") {echo "active"; }?>">
Store
</li>
<li class="nav-item <?php if ($current_page=="news") {echo "active"; }?>">
News
</li>
<li class="nav-item <?php if ($current_page=="contact") {echo "active"; }?>">
Contact
</li>
</ul>
I'm not saying this is the optimal method, but it works for me and it's simple to implement.
adding this:<?= ($activePage == 'home') ? 'active':''; ?> to my link it works perfectly, I only can't make the child of a submenu working to make the parent active.
Assume you have a navbar with the following items:
<ul>
<li id="menu-item-home">HOME</li>
<li id="menu-item-services">SERVICES</li>
<li id="menu-item-about-us">ABOUT US</li>
<li id="menu-item-contact">CONTACT</li>
</ul>
Then, declare a javascript variable in each page as below:
<script>
<?php echo("var active = 'menu-item-home';"); ?>
</script>
The variable "active" is assigned with the corresponding item of each page.
Now, you can use this variable to highlight the active menu item as below.
$(window).ready(function(){$("#" + active).addClass("active");});
I have a similar issue with my web app menu.
I also have sub menus which do not appear as top level menu buttons.
My solution is as follows:
a) Partial php file with menu html and a little php function at the top that checks GET variables against the menu buttons.
I have two GET variables to check: the page and (if necessary) the menu_button.
b) Adding any new php page with a href links to either menu pages or sub menu pages.
The variable "menu_button" is optional and can be used to link to submenu php files.
Of course the security concerning GET variables should be considered.
From my point of view, this solution has less effort than having to maintain an array of pages or links somewhere.
You just use a get variable "menu_button" where you pass the top level menu button that should be marked visually in any link which targets your php file.
Code examples:
Partial menu.php (has to be included in every php file):
<?php
function active($page_link){
$menu_button = $_GET("menu_button") ?: $_GET("page"); // sets the menu button either to the given top level menu or it defaults to the page itself
if($menu_button === $page_link) return "active";
}
?>
<div>
<a href="?page=one" class="<?= active('one') ?>"Link one</a>
Link two
</div>
Any php file with links to sub menu file:
<div>
Link one
Link to sub menu page "three" of menu "two"
</div>
Works for me. Hope someone else can use this.
For making a dynamic active menu link I follow this method.
first, In the menu link, I always use the full address:
//HTML CODE
<ul class="menu">
<li>
Home
</li>
<li>
About us
</li>
<li>
Contact
</li>
</ul>
//Javacript Code
const menus = document.querySelectorAll('.menu li a');
menus.forEach((menu) => {
const currentLocation = window.location.href;
if (currentLocation === window.origin) {
menus[0].classList.add('active');
} else if (menu.href === currentLocation) {
menu.classList.add('active');
} else {
return;
}
});
and then I will use vanilla javascript code to do the rest
You can use
<?php
function active($current_page){
$page = $_GET['p'];
if(isset($page) && $page == $current_page){
echo 'active'; //this is class name in css
}
}
?>
<ul>
<li><a class="<?php active('page1');?>" href="?p=page1">page1</a></li>
<li><a class="<?php active('page2');?>" href="?p=page2">page2</a></li>
<li><a class="<?php active('page3');?>" href="?p=page3">page3</a></li>
<li><a class="<?php active('page4');?>" href="?p=page4">page4</a></li>
</ul>

Can anyone suggest a way I can get my class="selected" to work on my navigation in Wordpress?

Can anyone suggest a way I can get my class="selected" to work on my navigation in Wordpress?
I have a wordpress navigation setup:
If I am on the home page, my home page class is selected.
If I want to go to page one, I want this class to change in thenavigation so only this class loads and not the home page.
I use: class="selected" to activate my roll over effect.
I can get this to work on a fixed site, just not on wordpress, any suggestions here?
<div class="nav">
<ul>
<li class="selected">Home</li>
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
</ul>
</div>
Could I use an if statement here?
<?php if(is_home() ) {
//for example load class="selected"
} else {
//for example if other page don't load class="selected"
} ?>
From what I understood, you're using a hardcoded navigation, and not wp_nav_menu() from WordPress.
So, you can conditionally check for each page you are using:
<div class="nav">
<ul>
<li<?php echo is_home()? ' class="selected"'; '';?>>
Home
</li>
<li<?php echo is_page('Contact')? ' class="selected"'; '';?>>
Contact page
</li>
<li<?php echo is_single('My first Post')? ' class="selected"'; '';?>>
Myfirst post
</li>
</ul>
</div>
You should make use of the Conditional Tags present in WordPress.
If you look at the first <li> you will see <?php echo is_home()? ' class="selected"'; '';?> This code is expressed as a ternary operator which is the equivalent of
if( is_home() ){
echo ' class="selected"'; #echo class. white space in front so that it does not stick to the "<li"
else{
echo ''; #do nothing
}
In the example above, I used three functions:
is_home() - Returns true if you are on the home page
is_page($arg) - Returns true if you are on the page specified by $arg.
is_single($arg) - Returns true if you are on the post specified by $arg.
There are other conditional tags available that you can choose to use.

Categories