Posts

add codes in child theme header

How to Add Codes in Child Theme Header

We are generally comfortable to add things as our wish in the header, even in the footer. Because the most themes are the parent theme. Premium themes come with extra options where you can add Google analytics codes, Meta tags, custom texts, phone number, even a search box etc. So in this post, you will learn about how to add codes in child themes header.

How to add codes in Child theme’s header.php

You may be wondering about copying the parent theme’s header.php and paste in the child theme. Yeah, it works. But when you can edit child theme’s functions.php, why do you need an extra header.php file? Well, let’s see how we can make it work using some codes.

Open your child theme’s functions.php and paste these codes.

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
    ?>
    //Add here HTML or JS codes
    <?php 
}

For an instance, you want to add Google Analytics codes within tags. Just add these codes in child’s functions.php

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
    ?>
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXX-X']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<?php 
}

You can also add shortcode too. Just like these

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
    
   echo do_shortcode("[shortcode]");
}

You can add some HTML codes too.

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
   ?> 
    <h4>It's a H4 title</h4>
    <a href="#"> Test Hyperlink</a>
  <?php
}

add codes in child theme header

If you want to insert a search form, here you go….

add_action('wp_head', 'mwp_header_code');
function mwp_header_code(){
  <?php get_search_form(); ?>
}

Check out these codes in Git

So, here you have learned how to add custom HTML, JS, PHP codes even some style in child theme’s header very easily. Just make sure you are adding contents in header specific DIV. Otherwise, it will be looking awkward.