Dynamic PHP Title Based On Page Name

Hi

I have searched for help on automatically adding the page tile of my pages based on the page name itself.

For Example:

Site Name | Page Name

So this page: www.sitename.com/about-us.php would return in the <title> tag:

My Site | About Us

I just cant find the right solution. Could somebody please help me on this?

Many Thanks :slight_smile:

Use a combination of [fphp]str_replace/fphp and [fphp]ucwords/fphp functions to turn about-us.php into “About Us”, but I dont see how you’d turn sitename.com to “My Site”

Hi

Thanks for the response, when I mentioned site name I meant for example “Sitepoint” or the name of the actual website.

I am a complete novice to PHP so I am really unsure how I would get this to work.

Thanks

Try something like this:


<?php
$page_title = 'SiteName | ' . ucwords(str_replace(array('-', '/', '.php'), array(' '), $_SERVER['PHP_SELF']));
?>
<html>
<head>
	<title><?= $page_title ?></title>
</head>
<body>

	<!-- whatever else you wanna put on your page -->
	
</body>
</html>

many Thanks for the reply.

I tried your code but it is outputting the following

<title>SiteName | Kingswoodprogrammesictsoundscape</title>

The reason being I think is because some of my pages are in directories for example “Programmes”

So I need it to be the following <title>SiteName | Programmes | ictsoundscape</title>

Any ideas as to how I would do this?

Thanks

I gave you a good example. Figure out the rest.

You had better post some example strings showing what they are at the moment vs what you want them to read, and maybe explain where are you getting the rest of the page content from and why you only want the title of the page to be dynamic. Why not the <h1></h1> heading too?

<?php

function fixTitle(&$input)
{
	$input = str_replace('-', ' ',$input);
	$pos = strpos($input,'.');
	if($pos > 0)
		$input = substr($input,0,$pos);
	$input = ucwords($input);
}

$aTitle = explode('/',trim($_SERVER['REQUEST_URI'],'/'));
$aTitle = array_reverse($aTitle);
array_walk($aTitle, fixTitle);
echo implode(' | ',$aTitle).' | PUT SITENAME HERE';

?>

For an url like: http://localhost/folder1/folder2/folder3/about-us.php it will output:

About Us | Folder3 | Folder2 | Folder1 | PUT SITENAME HERE

Maybe this can inspire you to create something nice.

Use The following code

<?php
$page = $_SERVER[‘REQUEST_URI’];
$pageName = str_replace(‘/’,‘’,$page);
$pageTitle = ucwords(str_replace(‘-’,’ ',$pageName));
?>
<html>
<head>
<title><?php echo $pageTitle;?></title>
</head>
<body>
<!-- Place you body contetn here–>
</body>
</html>