Dynamic meta and title php page

This article will show you how to create a handy dynamic meta tag, meta description and title for your web page. This is ideal if you are using includes and want to have different meta tags, meta descriptions or page titles on different pages of your website.

First off add this code to your main page for example home.php, (ideally near the top of the page, but it doesn’t matter too much)

<?php$title = "Your Page";
$keywords = "keywords, go, here";
$description = "A description for the meta tag";

require_once("header.php");  ?>

First off here we have our Title variable, change the title of the page you are dealing with by editing “Your Page”, the same goes with the keywords, which is the meta keywords of your website which search engines crawl, so if your website is advertising cars you may want to add keywords such as “tyres, new and used cars, car parts, etc” (note make sure each keyword is separated by a comma). Finally the description is what your website will be described as in a search. You want this to outline what your website is about, or what the current page is about.

After you have put the first bit of code in, you will want to put the code that calls the variables from an external file. I have used a require_once page as this will only need to be called once on each page. I called it header.php for examples sake.

header.php (require_once used for this in page.php)

<title><?php if(isset($title)) { print $title; } else { print "Default Title"; } ?></title>
 <meta http-equiv="keywords" content="<?php if(isset($keywords)) { print $keywords; } else { print "default,key,words"; } ?>" />
 <meta http-equiv="description" content="<?php if(isset($description)) { print $description; } else { print "Default Description!"; } ?>" />

This bit of code should go within your tags. You won’t need to edit this, you do it through the first piece of code.

About Nick

Front End Web Developer / Designer

  • Barabara

    Very interesting read! Thanks for the information Nick!

  • Donn Celi

    I just want to tell you that I am very new to blogging and truly enjoyed your web blog. Probably I’m planning to bookmark your blog . You actually come with superb writings. Thanks a bunch for sharing your web-site.

  • http://www.geekiest.net/ shiyon

    thanks a ton..!!..
    you have quickly provided me the solution.