Question

For my header.php file, I would like to grab the <title> via php and having trouble doing this. I know calling the constant would work, but that would mean I would need multiple files (which is bad practice). Any further help would be appreciated.

define("HOME", dirname(__DIR__)."index.php"); 
define("ABOUT", dirname(__DIR__)."../about/index.php"); 
define("WORK", dirname(__DIR__)."../work/index.php"); 
define("SERVICES", dirname(__DIR__)."../services/index.php"); 
define("CLIENTS", dirname(__DIR__)."../clients/index.php"); 
define("CONTACT", dirname(__DIR__)."../contact/index.php"); 

$page_titles = array (
    'home_page' => 'Home | Page',
    'about_page' => 'About | Page',
    'work_page' => 'Work | Page',
    'services_page' => 'Services | Page',
    'clients_page' => 'Clients | Page',
    'contact_page' => 'Contact | Page'
);

if (HOME == $page_titles[0]) {
    return $page_titles[0];
}

if (ABOUT == $page_titles[1]) {
    return $page_titles[1];
}

if (WORK == $page_titles[2]) {
    return $page_titles[2];
}

if (SERVICES == $page_titles[3]) {
    return $page_titles[3];
}

if (CLIENTS == $page_titles[4]) {
    return $page_titles[4];
}

if (CONTACT == $page_titles[5]) {
    return $page_titles[5];
}
Was it helpful?

Solution

Your page should define its own title. But, if you really want to do it this way, here's a possible solution:

whatever_page_you_load.php:

define("PAGE", "WHATEVERPAGE");

include("header.php");

header.php:

$page_names = array(
  "HOME" => "Home Page",
  "WHATEVERPAGE" => "Whatever Page's Name";
);

$title = "Default Title";

if(defined("PAGE") && !empty($page_names[PAGE])) {
  $title = $page_names[PAGE];
}

echo "<title>" . htmlentities($title) . "</title>";

OTHER TIPS

Your code looks like this after I switch names of variables with their values:

if (dirname(__DIR__)."index.php" == 'Home | Page'){
    return 'Home | Page';
}

The condition in the statement dirname(__DIR__)."index.php" == 'Home | Page' will never evaluate to true.

One example of having a specific title for a specific page is to pass page name in URL and then display page name accordingly:

$titles = [
    'home' => 'Home title',
    'contact' => 'Contact title',
    // Other titles omitted    
];

$page = 'home';
if (array_key_exists('page', $_GET) && array_key_exists($_GET['page'], $titles)){
    $page = $_GET['page'];
}

echo '<title>' . $titles[$page] . '</title>';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top