Add Custom Content within Head Tag

Without directly adding custom content within the <head></head> tag (header.php) in WordPress site, there are ways to add custom content using simple snippet. You can easily achieve this by writing your own function and simply hooking it up with an action (wp_head in this case) using “add_action” function. Here is a sample snippet.

add_action('wp_head','insert_custom_content');
function insert_custom_content() {
   echo 'Your custom content'; }

This snippet will add/show “Your custom content” message within the <head></head> tag. This may or may not be the best example to demonstrate the best use-case scenario but you get the idea. Perhaps adding Google Analytics code or simply a JavaScript/CSS could be a great option to get the most out of this snippet.

What Else?

Now, if you want to get little more creative with your snippet, you can do that too and the scopes are pretty much endless. Think of about a scenario where you need to add certain JavaScript library files. It could be for pages (page.php) or a very specific page, could be for your single post page (single.php). You can use simple conditional statement to do that. Here is an example.

add_action('wp_head','insert_custom_content');
function insert_custom_content() {
   // for single post page only
   if (is_single()){
      echo '<script src="https://domain.com/single.js"></script>'; }
   // for all pages
   if (is_page()){
      echo '<script src="https://domain.com/page.js"></script>'; } 
   // for "contact" page only
   if (is_page('contact')){
      echo '<script src="https://domain.com/contact.js"></script>'; }
}

All you need to do now is to copy this snippet within your current theme’s functions.php page and update it. Go back to the front-end of your site and refresh it. You should have your content.

Refrences: add_action, wp_head, Conditional Tags

Today In History

  •  
  •  

Comment

Leave a Reply

Note: Convet HTML, PHP, JavaScripts from HTMLify, before posting from comment section.
License: By submitting a comment here you grant this site a perpetual license to reproduce your words and name/Web site in attribution. Please use your real name or a pseudonym (i.e., pen name, alias, nom de plume) when commenting. If you add your site name, company name, or something completely random, I'll likely change it to whatever I want.