Best way to have a variable template in php - php

I'm coding a menu bar for a website in php. Because I don't want to have to edit it multiple times on the half a dozen or so pages I'll have I've decided to put it in it's own separate header.php file and just include_once(header.php) in the various pages.
My problem is that the menu is going to be slightly different depending on which page it's included in. Right now I'm dealing with it by having the following in my header.php file with $PageTitle being defined in the individual pages:
if ($PageTitle == "Home"){
echo '<li class="active">Home</li>';
}
else{
echo '<li>Home</li>';
}
if ($PageTitle == "About"){
echo '<li class="active">About</li>';
}
else{
echo '<li>About</li>';
}
...
The active class simply highlights the menu of the current page (Like the menu bar on the top of StackOverflow). It works fine but I'm curious if there is a better perhaps more efficient way to doing this. Thanks guys.

Try this:
//list of menu headers
$headers = new array();
//populate the array with your headers here ...
foreach($headers as $val)
{
if( $PageTitle == $val )
echo '<li class="active">'.$val.'</li>';
else
echo '<li>'.$val.'</li>';
}

for current class you can also use jquery if you want to:
$(function(){
var path = location.href;
if ( path )
$('.side_menu a[href="' + path + '"]').attr('class', 'current');
});

Related

Display static items according to page accessed, in PHP

I need to include some js, css type items in specific pages.
So far I've done the following:
define("DIR_ADMIN", "admin");
function fusion($location, $page, $type) {
$dirAdmin = DIRECTORY_SEPARATOR.DIR_ADMIN;
$change = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $location);
$changed = ucfirst($change);
$result = $dirAdmin.$changed;
if($type=='js'){
echo "<script src='$result'></script>\n";
} elseif($type=='css'){
echo "<link rel='stylesheet' href='$result' />";
} elseif($type=='favicon'){
echo "<link rel='shortcut icon' href='$result' />";
} elseif($type=='logo'){
echo "<img src='$result' alt='logo'>";
} else {
echo $result;
}
}
In HTML I called the function like this:
<?php fusion("/assets/vendors/js/vendor.bundle.base.js", "clients", "js"); ?>
First is the file URL, then the page, and finally the file type.
What I'm not able to come up with is the part that receives the value $page.
I created a routing system in php, so all files are accessed like this: index.php?page=clients, except in the case of the homepage which is just index.php.
I need that when the value of $page is set for example with clients it should load all items that have this same when the clients route is accessed.
In some cases the route may have another word attached, for example: index.php?page=clients-add, in which case it should check if there is only the word clients in $_GET.
And if I set the value of $page to all, it should display on all pages. How can I do this?
Within your fusion function you need to pick up which page you're on and then including the displaying of content after that.
Use this snippet to help dictate the page you're on.
$curr_page = "home";
if ( isset( $_GET["page"] ) ) {
$curr_page = $_GET["page"];
}
if ( $page == "all" || $page == $curr_page ) {
//echo items here
}

PHP include() wiping rest of HTML document?

So I have a simple html page that looks like this.
<html>
<head>
<?php include("scripts/header.php"); ?>
<title>Directory</title>
</head>
<body>
<?php include("scripts/navbar.php"); ?>
<div id="phd">
<span id="ph">DIRECTORY</span>
<div id="dir">
<?php include("scripts/autodir.php"); ?>
</div>
</div>
<!--Footer Below-->
<?php include("scripts/footer.php"); ?>
<!--End Footer-->
</body>
</html>
Now, the problem is, when I load the page, it's all sorts of messed up. Viewing the page source code reveals that everything after <div id="dir"> is COMPLETELY GONE. The file ends there. There is no included script, no </div>'s, footer, or even </body>, </html>. But it's not spitting out any errors whatsoever. Just erasing the document from the include onward without any reason myself or my buddies can figure out. None of us have ever experienced this kind of strange behavior.
The script being called in question is a script that will fetch picture files from the server (that I've uploaded, not users) and spit out links to the appropriate page in the archive automatically upon page load because having to edit the Directory page every time I upload a new image is a real hassle.
The code in question is below:
<?php
//Define how many pages in each chapter.
//And define all the chapters like this.
//const CHAPTER_1 = 13; etc.
const CHAPTER_1 = 2; //2 for test purposes only.
//+-------------------------------------------------------+//
//| DON'T EDIT BELOW THIS LINE!!! |//
//+-------------------------------------------------------+//
//Defining this function for later. Thanks to an anon on php.net for this!
//This will allow me to get the constants with the $prefix prefix. In this
//case all the chapters will be defined with "CHAPTER_x" so using the prefix
//'CHAPTER' in the function will return all the chapter constants ONLY.
function returnConstants ($prefix) {
foreach (get_defined_constants() as $key=>$value) {
if (substr($key,0,strlen($prefix))==$prefix) {
$dump[$key] = $value;
}
}
if(empty($dump)) {
return "Error: No Constants found with prefix '" . $prefix . "'";
}
else {
return $dump;
}
}
//---------------------------------------------------------//
$archiveDir = "public_html/archive";
$files = array_diff(scandir($archiveDir), array("..", "."));
//This SHOULD populate the array in order, for example:
//$files[0]='20131125.png', $files[1]='20131126.png', etc.
//---------------------------------------------------------//
$pages = array();
foreach ($files as $file) {
//This parses through the files and takes only .png files to put in $pages.
$parts = pathinfo($file);
if ($parts['extension'] == "png") {
$pages[] = $file;
}
unset($parts);
}
//Now that we have our pages, let's assign the links to them.
$totalPages = count($pages);
$pageNums = array();
foreach ($pages as $page) {
//This will be used to populate the page numbers for the links.
//e.g. "<a href='archive.php?p=$pageNum'></a>"
for($i=1; $i<=$totalPages; $i++) {
$pageNums[] = $i;
}
//This SHOULD set the $pageNum array to be something like:
//$pageNum[0] = 1, $pageNum[1] = 2, etc.
}
$linkText = array();
$archiveLinks = array();
foreach ($pageNums as $pageNum) {
//This is going to cycle through each page number and
//check how to display them.
if ($totalPages < 10) {
$linkText[] = $pageNum;
}
elseif ($totalPages < 100) {
$linkText[] = "0" . $pageNum;
}
else {
$linkText[] = "00" . $pageNum;
}
}
//So, now we have the page numbers and the link text.
//Let's plug everything into a link array.
for ($i=0; $i<$totalPages; $i++) {
$archiveLinks[] = "<a href='archive.php?p=" . $pageNums[$i] . "'>" . $linkText[$i] . " " . "</a>";
//Should output: <a href= 'archive.php?p=1'>01 </a>
//as an example, of course.
}
//And now for the fun part. Let's take the links and display them.
//Making sure to automatically assign the pages to their respective chapters!
//I've tested the below using given values (instead of fetching stuff)
//and it worked fine. So I doubt this is causing it, but I kept it just in case.
$rawChapters = returnConstants('CHAPTER');
$chapters = array_values($rawChapters);
$totalChapters = count($chapters);
$chapterTitles = array();
for ($i=1; $i<=$totalChapters; $i++) {
$chapterTitles[] = "<h4>Chapter " . $i . ":</h4><p>";
echo $chapterTitles[($i-1)];
for ($j=1; $j<=$chapters[($i-1)]; $j++) {
echo array_shift($archiveLinks[($j-1)]);
}
echo "</p>"; //added to test if this was causing the deletion
}
?>
What is causing the remainder of the document to vanish like that? EDIT: Two silly syntax errors were causing this, and have been fixed in the above code! However, the links aren't being displayed at all? Please note that I am pretty new to php and I do not expect my code to be the most efficient (I just want the darn thing to work!).
Addendum: if you deem to rewrite the code (instead of simply fixing error(s)) to be the preferred course of action, please do explain what the code is doing, as I do not like using code I do not understand. Thanks!
Without having access to any of the rest of the code or data-structures I can see 2 syntax errors...
Line 45:
foreach ($pages = $page) {
Should be:
foreach ($pages as $page) {
Line 88:
echo array_shift($archiveLinks[($j-1)];
Is missing a bracket:
echo array_shift($archiveLinks[($j-1)]);
Important...
In order to ensure that you can find these kinds of errors yourself, you need to ensure that the error reporting is switched on to a level that means these get shown to you, or learn where your logs are and how to read them.
See the documentation on php.net here:
http://php.net/manual/en/function.error-reporting.php
IMO all development servers should have the highest level of error reporting switched on by default so that you never miss an error, warning or notice. It just makes your job a whole lot easier.
Documentation on setting up at runtime can be found here:
http://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors
There is an error in scripts/autodir.php this file. Everything up to that point works fine, so this is where the problem starts.
Also you mostlikely have errors hidden as Chen Asraf mentioned, so turn on the errors:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Just put that at the top of the php file.

Fail to using if/else to hover image by dynamic url

I'm using the basic way to doing the hover image as the CSS method doesn't work for me. Current I'm using the if/else statement to do so. If the contain the URL like abc.com it will hover the image.
But now I only can hover the group url but if there is sub categories in groups I won't able to hover, how can I do it all the activity inside the group, the image will hover?
How to doing if the URL contain the words or path. For example abc.com/groups/* it will hover the groups. Similar like we doing searching in MySQL the words/variable as using "%".
<?php
$request_url = apache_getenv("HTTP_HOST") . apache_getenv("REQUEST_URI");
$e = 'abc.com/dev/';
$f = 'abc.com/dev/groups/';
$g = 'abc.com/dev/user/';
?>
<div class="submenu">
<?php
if ($request_url == $e) {
echo '<div class="icon-home active"></div>';
} else {
echo '<div class = "icon-home"></div>';
}
?>
<?php
if ($request_url == $f) {
echo '<div class="icon-groups active"></div>';
} else {
echo '<div class = "icon-groups"></div>';
}
?>
</div>
I propose a javascript way to do so, with jQuery
$("a[href*='THE_URL_PATTERN_YOU_WANT_TO_MATCH']").children(".icon-home").addClass("active");
BTW, it is NOT a good idea to wrap a div into a a tag.

PHP + Wordpress: Auto list image name into dropdown slection

I am creating wordpress theme option panel and want to use some icons. I have one directory dedicated for icon into my theme folder. What I want to do is if user add any new image into that folder it will automatic appear into dropdown selection list into theme option panel.
Is there any way to do this in PHP with Wordpress? I believe that is possible as I saw one theme has the same option but it was so complex so couldn't figured out that and don't remember theme name too now.
I have to use it with below type of code
$video_tax = array(-1 => 'Choose a category');
$video_terms = get_terms('video_category');
if ($video_terms) {
foreach ($video_terms as $video_term) {
$video_tax[$video_term->term_id] = $video_term->name;
}
}
You might want to start by having a look at scandir. This will list all the contents of a folder on your system. From there it would just be a matter of putting the correct path, url or whatever you want in the the value of your options.
EDIT: Here's some sample code from one of my plugins:
function icons_meta(){
global $post;
$custom = get_post_custom($post->ID);
$link = $custom["icon"][0];
$files = scandir(PATH."/icons");
$selected = '';
echo "<select name='icon'>";
foreach($files as $file){
if($file == $link){
$selected = 'selected="selected"';
} else {
$selected = '';
}
echo "<option value='$file' $selected>".$file."</option>";
}
echo "</select>";
}

Wordpress dynamic navigation function for highlighting single post tabs

I am trying to write a function which I can re-use in my WordPress themes that will allow me to build robust dynamic navigation menus. Here is what I have so far:
function tab_maker($page_name, $href, $tabname) {
//opens <li> tag to allow active class to be inserted if tab is on proper page
echo "<li";
//checks that we are on current page and highlights tab as active if so
if(is_page($page_name)){
echo " class='current_page_item'>";
}
//closes <li> tab if not active
else {
echo ">";
}
//inserts the link as $href and the name of the tab to appear as $tabname then closes <li>
echo "<a href=$href>$tabname</a>";
echo "</li>";
}
This code works as expected except I cant enable it to highlight for a single blog post as the page names are dynamic.
I know about the WordPress function is_single() which I've used to implement this feature in previous nav menus but I can't find a way to integrate it into this function.
I can see were your going with this,
inside your if statement for the is_page
can you use,
function tab_maker($name, $href, $tabname) {
if(is_page($name)){
echo " class='current_page_item'>";
}else **if(is_single($name)){
echo " class='current_page_item'>";**
}else{
echo ">";
}
echo "<a href=$href>$tabname</a>";
echo "</li>";
}
haven't tried this myself

Categories