The header.php file is one of the most important template files in a WordPress theme. It defines the HTML document structure, loads essential theme assets using wp_head(), and displays the site’s header, including the logo and navigation menu.
In this example, the header template includes responsive meta tags, Adobe Fonts, Google Analytics integration, a dynamic logo retrieved using Advanced Custom Fields (ACF), and a responsive navigation menu registered with wp_nav_menu(). It also uses wp_body_open() and body_class() to follow WordPress theme development best practices.
Add the following code to your theme’s header.php file to create a dynamic and responsive website header.
<?php
/**
* The header for our theme
*
* This is the template that displays all of the <head> section and everything up until <div id="content">
*
* @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
*
* @package qrs
*/
?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="https://gmpg.org/xfn/11">
<!--<link rel="stylesheet" href="https://use.typekit.net/wdh7ylz.css">
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">-->
<link rel="stylesheet" href="https://use.typekit.net/msd3nqy.css">
<?php wp_head(); ?>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-9NKWRSS783"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'G-9NKWRSS783');
</script>
</head>
<body <?php body_class(); ?> >
<?php wp_body_open(); ?>
<div id="page" class="site">
<header id="masthead" class="site-header">
<div class="container">
<div class="logo">
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php $header_logo = get_field('header_logo','option');
if (!empty($header_logo)) {
echo '<img src="' . esc_url( $header_logo['url'] ) . '" alt="' . $header_logo['alt'] . '">';
} else {
echo '<h1>' . get_bloginfo('name') . '</h1>';
} ?>
</a>
</div>
<nav id="site-navigation" class="main-navigation">
<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">
<span></span>
<span></span>
<span></span>
</button>
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-1',
'menu_id' => 'primary-menu',
)
);
?>
</nav><!-- #site-navigation -->
</div>
</header><!-- #masthead -->
<div class="main-site">