Search code examples
phpheaderincludemeta-tags

PHP header - adding different metatags per page


I have a commom php header. I would like to add page specific META.

Currently my header looks like this.

<?php include ('includes/pageheader.php'); ?>

It currently uses a long if statemment

<?php $page =  $_SERVER['REQUEST_URI']; 
if($page == "/") {
  ?>
<!-- Metadata for home -->
?>

I was wondering if there was a better way or a class to be able to build up page specific meta to this header.


Solution

  • In your header, you could do something like this.

    <?php if(isset($header)): ?>
      <?php foreach($header as $tag): ?>
        <?= $tag ?>
      <?php endforeach ?>
    <?php endif ?>
    

    Then above your include, you could add.

    <?php
    $header[] = '<meta charset="UTF-8">';
    $header[] = '<meta name="description" content="Free Web tutorials">';
    $header[] = '<meta name="keywords" content="HTML,CSS,XML,JavaScript">';
    $header[] = '<meta name="author" content="John Doe">';
    $header[] = '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
    include ('includes/pageheader.php');
    ?>