How best to add code to header

I’d like to place the Google ads code to my header.

<script data-ad-client="ca-pub-7290301843408108" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

What’s the best way of doing this? Header.php in my child theme? I don’t yet have a header.php in my child theme so should I just copy the above code in a new php file, name it header and ftp to my child theme? Or do I need to set up my header like this:

add_action('wp_head','custom_javascript');
function custom_javascript () { ?>

<script data-ad-client="ca-pub-7290301843408108" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<?php }

Hi @demonboy,

Thanks for reaching out.

The second one is the best one since it’s just an embed code. Modifying the existing templates like the header is only good design or feature customization. The second one is also better for changing priorities where there are plugins causing conflicts, like simply modify the priority in case you need to execute it at the very last skipping the conflict. In which you can’t do with the templates since you ignore wp_head.

Cheers!

OK, so since I don’t have a header in my child theme yet, shouldn’t the above code be wrapped in php or JS? What would be the complete code for creating a new header.php?

Hi @demonboy,

Ah, I understand now. The ads rendering is part of that code instead of the separate javascript code. It actually depends on where you wish to display it, is it in the header but not within header structures? Or above or below header? Hence, the best code will be based on where you wish to implement it. For now, let’s say you wish to add it below the header, then you can simply add this to the child theme’s functions.php without directly creating or editing header template.

add_action('x_after_masthead_end','custom_javascript');
function custom_javascript () { ?>

<script data-ad-client="ca-pub-7290301843408108" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<?php }

If it’s not what you’re looking for, then please provide the details where you intend to display the ads. Creating your own header template is okay, but still not worth for this few line of codes. The files responsible for that are in folder \x\framework\views\header which you can then copy to your child theme.

Thanks!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.