Adding a stylesheet and javascript in wordpress.

In wordpress stylesheet and javascript can be added in the traditional conventional way.

For eg this

But problem arises when we go for child themes.

If we build a child theme, it inherits all of its theme templates from the parent theme, unless we give it its own copy of a particular template. So if we copy our parent theme’s header.php into our child theme, so that we can add the Google Web Fonts code to it, then any changes made to the parent theme’s header.php will no longer be applied to our child theme.

So what we want to do is insert the code dynamically into the header, so that we don’t need to edit the header.php template at all. We do this in functions.php

The difference here is that in a child theme, functions.php doesn’t override the parent functions, it runs in addition to them. So any functions in our child theme will run after all the functions in the parent theme have been runned.

So, to dynamically insert the Google Web Fonts code into the header, we use the wp_enqueue_style function.

The code for this will be somewhat like this:

function load_fonts(){wp_register_style(‘googleFonts’,‘

http://fonts.googleapis.com/

…’);wp_enqueue_style(‘googleFonts’);}

  

add_action(‘wp_print_styles’,‘load_fonts’);We create a function, load_fonts, which registers the stylesheet declaration under the name ‘googleFonts’, using the URL provided by Google. It then enqueues the style ready to spit it out into the header. The add_action part does the actual spitting.

Now the code that Google gave us will be automatically included in our header, and your child theme will still inherit the parent’s header.php

It’s good practice to add any additional stylesheets to our theme in this way, and the same goes for scripts, which can be added in a similar way using thewp_enqueue_script function.

Using these methods will keep your themes portable and plugin-friendly.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!