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.

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.

function insert_custom_content() {
   // for single post page only
   if (is_single()){
      echo '<script src=""></script>'; }
   // for all pages
   if (is_page()){
      echo '<script src=""></script>'; } 
   // for "contact" page only
   if (is_page('contact')){
      echo '<script src=""></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


Commenting is disabled.