How to properly build a navigation menu that highlights the current page - php

I've setup a menu for a fairly simple site based on icant.co.uk. It's fairly simple with maybe 5 pages. The small site is mainly a mysql browser for a few tables using MATE. Theres a common.php file that contains the header & footer HTML so thats where I put the code below.
The code below highlights the current page on the menu. Its ugly and I'm sure there has to be a better way to do it.
Any help is appreciated, thank you!
heres my code
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
if ($currentFile == "orders.php"){
echo '<li id="active">Orders</li>';
}
else{
echo '<li>Orders</li>';
}
if ($currentFile == "customers.php"){
echo '<li id="active">Customer List</li>';
}
else{
echo '<li>Customer List</li>';
}
if ($currentFile == "order_details.php"){
echo '<li id="active">Order Details</li>';
}
else{
echo '<li>Order Details</li>';
}
?>
UPDATE For those curious, below is the working code!
<?php
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "order_details.php", "title" => "Order Details"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$currentAppend = ($page['file'] == $currentFile) ? ' id="current' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;
?>

What I normally do is something like (for all elements...):
<li class="<?php if (condition) echo 'selected'; ?>">content part, links, etc.</li>

Not sure if that's what you meant, but this way you'll get rid of this ugly if-else:
$currentFile = Explode('/', $_SERVER["PHP_SELF"]);
$currentFile = $currentFile[count($currentFile) - 1];
// easier to manage in case you want more pages later
$pages = array(
array("file" => "orders.php", "title" => "Orders"),
array("file" => "customers.php", "title" => "Customer List")
);
$menuOutput = '<ul>';
foreach ($pages as $page) {
$activeAppend = ($page['file'] == $currentFile) ? ' id="active"' : "";
$menuOutput .= '<li' . $activeAppend . '>'
. '' . $page['title'] .''
. '</li>';
}
$menuOutput .= '</ul>';
echo $menuOutput;

A more concise way of doing it (if you have short tags enabled) would be:
<li class="<?= $test=="your_page_name" ? 'selected' : 'not_selected'?>">Link Name</li>
It performs the same function as the first answer, just more concisely.

Here's a snippet from a project of mine. It it old ugly code, and uses tables, but you can just as easily use the idea for divs and cleaner markup. The trick is to make the navigation use a different class if the current page matches it's url.
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_home.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_home.php'>Billing Home</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_schedules.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_schedules.php'>Billing Schedules</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_outstanding.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_outstanding.php'>Outstanding</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_list.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_list.php'>List All</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_history.php'>Billing History</a></td></tr>
<td><a class='LeftSubNavLink<?php if($_SERVER["SCRIPT_NAME"] == "/admin/billing_statement_history.php"){print("Current");}?>' href='<?php print(MAIN_URL); ?>admin/billing_statement_history.php'>Statement History</a></td></tr>

Related

how use enclosing shortcodes in php ( wordpress theme )

edd restrict content plugin creates this shortcodes and these are working in pages and posts :
[edd_restrict id="any"]sample restricted html or text[/edd_restrict]
but i want to use it in my theme not in the posts or pages.
i tried this :
<?php =echo do_shortcode( '[edd_restrict id="any"]' . sample text . '[/edd_restrict]' );?>
but theme shows me fatal error.
so how can i use this shortcodes in wordress theme?
sample text here will be a php code that i want to restrict.
let me tell you more... i want to put the line below between those shortcodes in my single.php in wordpress :
<li><?php if(get_post_meta($post->ID, 'download',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download',true)."' > دانلود با لینک مستقیم</a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download32',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download32',true)."'>لینک مستقیم نسخه 32bit / </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'download64',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'download64',true)."'>لینک مستقیم نسخه 64bit </a> ";} else { echo ""; } ?>
<?php if(get_post_meta($post->ID, 'downloadwin',true)!= ""){echo "<a href='".get_post_meta($post->ID, 'downloadwin',true)."'>دانلود نسخه ویندوز </a> ";} else { echo ""; } ?></li>
The method do_shortcode accepts a string of a shortcode and it's attributes/content. So for example
<?php
$string = "some value or <b>html</b>";
// or (?)
$string = include TEMPLATEPATH . "/post-ads.php";
// or (!)
ob_start();
include TEMPLATEPATH . "/post-ads.php";
$string = ob_get_clean();
// for a specific use case:
if (get_post_meta($post->ID, 'download', true) != "") {
$string = "<a href='" . get_post_meta($post->ID, 'download', true) . "' >download</a> ";
} else {
$string = "";
}
if (get_post_meta($post->ID, 'download32', true) != "") {
$string2 = "<a href='" . get_post_meta($post->ID, 'download32', true) . "'>download 32bit / </a> ";
} else {
$string2 = "";
}
// after you have string:
echo do_shortcode('[edd_restrict id="any"]' . $string . '[/edd_restrict]');

How can I remove nested nav from all top-level listed items, except for Services in a PHP array?

I am trying to remove the nested list ($subPages) from displaying under all of the top-level lists ($pages), except for Services; however my code is allowing the nested list items to display under all three top-level list items.
Can anyone help me remove the nested list items from all top-level list items, except for one?
NB. I am new to PHP, and would like to just stick to PHP without any other languages. My PHP code may be in efficient; if you spot room for improvement, let me know.
<nav class="navBar wAuto fRight positAb">
<?php
$pages = array(
'/about/' => 'About',
'/services/' => 'Services',
'/book-a-service/' => 'Book a service'
);
$subPages = array(
'/services/bathroom-installation' => 'Bathroom installation',
'/services/boiler-repair' => 'Boiler repair',
'/services/boiler-service' => 'Boiler service',
'/services/gas-oil' => 'Gas & oil',
'/services/heat-recovery' => 'Heat recovery',
'/services/heating-plumbing' => 'Heating and plumbing',
'/services/rainwater-harvesting' => 'Rainwater harvesting',
'/services/solar-solutions' => 'Solar solutions',
'/services/underfloor-heating' => 'Underfloor heating'
);
$activePage = $_SERVER['REQUEST_URI'];
echo '<ul>';//open nav
foreach( $pages as $url => $anchor){
$activeClass = ($_SERVER['REQUEST_URI'] == $url) ? " active" : "";
echo '<li class="fLeft"><a class="font13'.$activeClass.'" href="'.$url.'"';
if($url == '/services/'){
echo 'id="parent"';
}
if($url == '/book-a-service/')
echo 'id="ctaUHP"';
echo '>'.$anchor.'</a>';
//Open nested nav
if(isset($url) == '/services/'){
echo '<ul class="wAuto positAb">';
foreach ($subPages as $url => $anchor){
echo '<li class="fullWidth"><a class="font10" href="'.$url.'"';//open nested nav
echo '>'.$anchor.'</a></li>';
}
};
echo '</li></ul>'; //close nested nav
}
//Close submenu
echo '</ul>';
//close nav
?>
</nav>
In the code for open nested nav, change if(isset($url) == '/services/') to if($url == '/services/'){
Explanation: You don't need to verify if the $url is set, you just need to print the nested nav when your $url == '/services/', that's why you need to remove the function isset() :)
EDIT
You lacked some {} and I even rearranged some of your code, so now looks like this :)
echo '<ul>'; //open nav
foreach( $pages as $url => $anchor) {
$activeClass = ($_SERVER['REQUEST_URI'] == $url) ? " active" : "";
echo '<li class="fLeft"><a class="font13'.$activeClass.'" href="'.$url.'"';
if($url == '/services/') {
echo 'id="parent"';
}
if($url == '/book-a-service/') {
echo 'id="ctaUHP"';
}
echo '>'.$anchor.'</a>';
//verify if exists nested nav
if($url == '/services/') {
echo '<ul class="wAuto positAb">'; //open nested nav
foreach ($subPages as $url => $anchor) {
echo '<li class="fullWidth"><a class="font10" href="'.$url.'">'.$anchor.'</a></li>';
}
echo '</ul>'; //close nested nav
}
echo '</li>';
}
echo '</ul>'; //close nav

php navigation using get or include

index.php is controlling the site.
I have elseif include based on variable $p
right now $p does not have anything in it and i'm not understanding why.
Also is using include the industry standard or would GET be a better choice?
In the header file which is included on index.php but it just takes me to the page link instead of storing the page in $p
<?php
$pages = array(
"home" => "HOME",
"services" => "SERVICES",
"employees" => "EMPLOYEES",
"contact" => "CONTACT");
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
echo '<li ';
if ($p == $url) { echo '<li><a class="active" href="' . htmlspecialchars(urlencode($url)). '.php">'
. htmlspecialchars($label) . '</a></li>'; } else { echo '<li>' . $label . '</li>'; }
}
?>
This is the index.php file:
<?php include('includes/header.php'); ?>
<?php
if ($p == "services") {
include("services.php");
} elseif($p == "employees") {
include("employees.php");
} elseif($p == "contact") {
include("contact.php");
} else {
include("home.php");
};
?>
<?php include('includes/footer.php'); ?>
It really depends on what you are trying to do. Maybe I am misunderstanding your question, however include and $_GET are two completely separate things.
$_GET is an array of the query string out of your URL. So, for instance, if your URL was mysite.com/index.php?a=rawr&p=services then $_GET would be array("a" => "rawr", "p" => "services"); If you don't have any parameters in your URL assigned to p, then $_GET["p"] would be empty
Source:
http://www.php.net/manual/en/reserved.variables.get.php
EDIT:
I think I'm starting to understand your question now. Using your current method would be fine, I would just change up the code slightly:
<?php
$pages = array(
"home" => "HOME",
"services" => "SERVICES",
"employees" => "EMPLOYEES",
"contact" => "CONTACT"
);
$p = (isset($_GET['p'])) ? $_GET['p'] : "";
foreach ($pages as $url => $label) {
?>
<li><a <?= $p == $url ? 'class="active"' : ""?> href="index.php?p=<?=$url?>" > <?=$label?> </a></li>
<?php
}
?>

Active Page for CSS using PHP and MYSQL

I am trying to build a menu with an active page element for CSS using PHP and MySQL.
This example PHP/HTML hybrid works, and is what I'm trying to mimic.
<nav><ul>
<li<?php if ($thisPage == "1") echo " class=\"active\""; ?>>page 1</li>
<li<?php if ($thisPage == "2") echo " class=\"active\""; ?>>page 2</li>
<li<?php if ($thisPage == "3") echo " class=\"active\""; ?>>page 3</li>
</nav></ul>
I want to blend this statement to set the active class:
<?php if ($thisPage == $menuID) echo " class=\"active\""; ?>
Into this unordered list statement
<?php
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
?>
This is where I am but I can't seem to get the syntax to work correctly.
echo "<li" . "if(" . $thisPage==$menuID . ")". echo ' class=\"active\"';" . ">" . "" . $row_rsMenu['menuName'] . "</li>\n";
If someone could help me to understand where this went wrong I'd appreciate it.
You have your if statement encapsulated in quotes. That means that PHP won't interpret it. Instead, it will print it out along with your HTML.
Something along the lines of this will work better:
echo "\n<nav>\n";
echo "<ul>\n";
while($row_rsMenu = mysql_fetch_assoc($rsMenu))
{
$active = ""; //not active by default
if($thisPage==$menuID){
$active = ' class="active" ';
}
echo "<li>" . "" . $row_rsMenu['menuName'] . "</li>\n";
}
echo "</ul>\n";
echo "</nav>\n";
By the way, where are you getting $menuID from?
Your error is wrapping the if block within quotes, among a few other issues with quotes.
Try this instead:
echo '<li', (($thisPage==$menuId) ? ' class="active"' : ''), '>', '', $row_rsMenu['menuName'], '</li>';
This uses a ternary operator to shorten things up a bit, in addition to fixing your syntax error.

changing colors when link is clicked

If I have a menu set up in the header which I use for most of my pages as "include/header.php" how do I setup so when I click on a link, it goes to that page, and that link changes colors (and shows as active)? Would jquery be good? or PHP?
Thanks!
You could use PHP to add a class to the current button by comparing it's URL, and the current page URL from $_GET. Without knowing what your URL structure is like, I can't say much more than that.
For example, using an array with button text and URLs:
$links = array('Home' => 'home', 'About' => 'about');
foreach($links as $text => $page)
{
if($_GET['page'] == $page)
{
echo '' . $text . '';
}
else
{
echo '<a href="/index.php?page=' . $page . '>' . $text . '</a>';
}
}
This code will add a class of current to the button who's page matches the value in $_GET. This might not exactly fit your needs due to you probably having a different URL structure, among other things, but it gives a basic explanation and example of how to do this.
Use php, you could write a function before your include like so,
function activeLink ($page) {
if ($page = 'home') echo ' class="active"';
elseif ($page = 'about') echo ' class="active"';
elseif ($page = 'posts') echo ' class="active"';
}
And in your header file,
echo '<a href="#"' . activeLink($page) . '>Home</a>
<a href="#"' . activeLink($page) . '>About</a>
<a href="#"' . activeLink($page) . '>Posts</a>';
And on your actual page;
$page = 'home';
include('header');
This will do the trick.

Categories