Add Scripts to WP Header.php with Functions.php

Sometimes we need to add references to scripts, metatags or conditional styles to the WordPress <head></head> section in header.php. WordPress has an action hook for this purpose. It’s very easy to use.

To add scripts, conditional styles or links to header.php, use the wp_head() action hook, like this:

add_action('wp_head', 'function_name');

function function_name() {

  echo "\n"; /* New line */
  /* function content */
  echo "\n"; /* New line */

}

For example, IE9 struggles with CSS gradients so if you use ColorZilla to create a CSS gradient you will need to add a conditional style to wp_head() along with a gradient class (.gradient) to your elements with gradients. To add the style condition to wp_head, do this:

add_action('wp_head', 'ie9_css_gradient_fix');

function ie9_css_gradient_fix() {

echo "\n".'<!--[if gte IE 9]>
  <style type="text/css">
    .gradient {
       filter: none;
    }
  </style>
<![endif]-->'."\n";

}

Will show you how to add the gradient class in a different post.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of

Free to your inbox

Join our mailing list to receive the latest news and updates from JournalXtra.

You have Successfully Subscribed!