WordPress: Css Styles and Javascripts in theme development (In depthish).
Tags: wordpress, tutorial, webdev, javascript
Published: 2019-05-02 18:08:47

---
title: WordPress: Css Styles and Javascripts in theme development (In depthish).
published: true
description: An in-depth(ish) tutorial into using Css Styles and Javascripts in WordPress theme development.
canonical_url: https://since1979.dev/wordpress-css-styles-and-javascripts-in-theme-development-in-depth/
cover_image: https://cdn-images-1.medium.com/max/2400/1*uAx2QKjKrqnQO3EMAOYitA.jpeg
tags: #wordpress, #tutorial, #webdev, #javascript
---

[Originally posted on my website February 21 2019](https://since1979.dev/wordpress-css-styles-and-javascripts-in-theme-development-in-depth/)

### Adding Css and Javascript to WordPress themes.

In this tutorial I will show you “the right way” to include Css styles and Javascripts in your WordPress themes. If you have previously created websites without WordPress, you are probably used to using _link href=“”_ and _script src=“”_ tags. While there is nothing that prevents you from inserting these tags into your themes directly, this is considered a “bad habit” in WordPress development.

WordPress has its own specific way to handle Css styles and Javascripts through the [_wp_enqueue_style()_](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) and [_wp_enqueue_script()_](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) family of functions.

Doing things the WordPress way will be a little bit more code to write, but has some real advantages over the direct use of tags, such as reusability of code, basic dependency management and the fact that, if you insert your Css styles and Javascripts correctly, plugins can take control over them for all kinds of purposes, such as, minification and concatenation.

Lets get started…

### Adding Css Styles to WordPress themes:

To add stylesheets we first need to hook into the WordPress process. If you want to know all the nuts and bolts about WordPress hooks check out [this article](https://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers), but in short… Hooks are like asking a chef to call upon you at a certain point of the cooking process. For instance asking him to call you when it is time to add vegatables to the soup, so you can add your own favourite one. In our case WordPress is cooking up webpages and we want to be called when it is time to collect styles and scripts (enqueue_scripts) so we can add our own.

#### Hooking into WordPress:

Add [the following code](https://gist.github.com/vanaf1979/1af64cb7e9c0e2a9d3f54ad17977cdf9) to your theme’s _functions.php_

{% gist https://gist.github.com/vanaf1979/1af64cb7e9c0e2a9d3f54ad17977cdf9 %}

You can hook into WordPress with either a Filter or an Action. Filters let you **change** something (We’ll come to these later), and Actions let you **do** something. In our case we need to **do** something (Add styles) so we use the _add_action()_ function to add an action to the _wp_enqueue_scripts_ hook, and register the callback function _my_theme_enqueue_styles()_ which will be executed when its time to collect Css styles or Javascripts from your theme.

The add_action() function takes 4 parameters:

*   **$tag:** The name of the action to which the callback function is hooked.
*   **$function_to_add:** The name of the callback function you wish to be called.
*   **$priority:** Used to specify the order in which the functions associated with a particular action are executed.
*   **$accepted_args:** The number of arguments the callback function accepts.

Notice that in this case we dont need the last two parameters so we don’t pass them, but we’ll get to them later.

To avoid name collitions its a good practice to prefix your function names with your themes name. So, if your theme is called “personal-theme” rename the above callback function to “_personal_theme_enqueue_styles_”, and change the name in the _add_action()_ function accordingly.

This piece of code won’t do very much yet, so lets start adding stylesheets. As an example in this tutorial I’m going to add the [PureCss framework](https://purecss.io/). You can change this to Bootstrap or whatever Css you like.

#### Enqueue a remote Css stylesheet:

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/41a72c8795590a6622a908892fec2241) from line 6 below:

{% gist https://gist.github.com/vanaf1979/41a72c8795590a6622a908892fec2241 %}

To add a stylesheet we use _the_ [_wp_enqueue_style()_](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) function which accepts 5 parameters. I’ll explain these from left to right:

*   **$handle:** Every stylesheet (or script) in WordPress needs a unique name so you, or a plugin, can refference it later. Here it’s also a good practice to prefix these with your theme name.
*   **$src:** A URL to you stylesheet. This can also be a local path, but we’ll get to that later.
*   **$deps:** An array of stylesheet handles this stylesheet depends on.
*   **$ver:** A string specifying the stylesheet version number, this will be added to the URL as a query string to bust out of caching by browsers and CDN’s .
*   **$media:** The [mediatype](https://www.tutorialspoint.com/css/css_media_types.htm) for this stylesheet. Like ‘all’, ‘print’ and ‘screen’, or media queries like ‘(orientation: portrait)’ and ‘(max-width: 640px)’.

The above code will “Enqueue/Add” the new stylesheet and WordPress will output the following link tag into the head of your webpages:

{% gist https://gist.github.com/vanaf1979/6bc3ff0dc84d21fedb4c53cd82a8e7ee %}

#### Adding Conditional stylesheets:

PureCss requires two conditional stylesheets for it’s responsive grid to function. One stylesheet for Internet Explorer 8, and One for any browser above IE8

Change the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/f9443c407695fa48ae341563b03bcb74) on lines 8 to 12.

{% gist https://gist.github.com/vanaf1979/f9443c407695fa48ae341563b03bcb74 %}

Here we simply enqueue two more stylesheets like we did before, but straight after that we add conditions via the [_wp_style_add_data()_](https://developer.wordpress.org/reference/functions/wp_style_add_data/) function. This function Accepts three parameters. I’ll explain these from left to right:

*   **$handle:** Name/handle of the stylesheet.
*   **$key:** Name of the data point for which we’re storing a value. Accepts ‘conditional’, ‘rtl’ , ‘suffix’, ‘alt’ and ‘title’.
*   **$value:** String containing the data to be added.

The code will now enqueue and output two more stylesheets in the head of your webpages with conditional comment:

{% gist https://gist.github.com/vanaf1979/6eb294b3daa7f555de9c6d62eff791c6 %}

#### Enqueue a local Css stylesheet:

To enqueue a local Css stylesheet we use the same process of adding a remote one, with one little addition.

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/57571fe568f7fcd265b861f81cb29e97) from line 14 below:

{% gist https://gist.github.com/vanaf1979/57571fe568f7fcd265b861f81cb29e97 %}

Here you see that the process is the same. We use the _wp_enqueue_style()_ function again, but make use of the [_get_template_directory_uri()_](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) function within the _$src_ parameter. This function returns an full url to your custom themes folder, making sure your urls dont break when you rename your theme or theme folder.

The code will now enqueue and output the extra local stylesheets in the head of your webpages with a full url like below:

{% gist https://gist.github.com/vanaf1979/6ccd19b1129fd443009e1e007cdcc212 %}

#### Enqueue inline Css styles:

There may be times where you need to inline a piece of Css. This could be the case when you need to add styles which depend on some wordpress setting, or where your styles depend on some other data.

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/6930f53d592fc464a91151a25f5b9343) from line 16 to 18 below:

{% gist https://gist.github.com/vanaf1979/6930f53d592fc464a91151a25f5b9343 %}

Here we first register the style using [_wp_register_style()_](https://codex.wordpress.org/Function_Reference/wp_register_style) with a handle only, so we can add data to it before enqueueing. We then add the Css we want to inline with the [_wp_add_inline_style()_](https://codex.wordpress.org/Function_Reference/wp_add_inline_style) function. _This_ function accepts two parameters:

*   **$handle:** The name of the script to which to add the extra styles.
*   **$data:** String containing the Css to be added.

Finaly we enqueue the style using the _wp_enqueue_style()_ function again passing just the handle name.

The code will now enqueue and output the inline styles in the head of your webpages like shown below:

{% gist https://gist.github.com/vanaf1979/269217f9f28eb72fe3508227bc0283f6 %}

### Adding Javascripts to WordPress themes:

The process of adding Javascript to your theme is very similar to adding styles, but there are some small differences and extra options.

#### Hooking into WordPress again:

Lets start by adding another hook to your _functions.php_. You could very well use the hook we just used for the styles, but I advise you to keep things seperated for the sake of maintainability.

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/a85567bcd08eac6ca2b23ec82cb278c0) from line 4 to 9 below:

{% gist https://gist.github.com/vanaf1979/a85567bcd08eac6ca2b23ec82cb278c0 %}

Here we create a new callback function called _my_theme_enqueue_scripts()_ and register it to the _wp_enqueue_scripts_ hook, just like we did for the styles.

Again this doesn’t do much yet so let’s add the first Javascript file.

#### Enqueue a Javascript file:

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/5a5a2ca0df529d3cea4964787940bd23) from line 6 below:

{% gist https://gist.github.com/vanaf1979/5a5a2ca0df529d3cea4964787940bd23 %}

Instead of using the _wp_enqueue_styles()_ function we now use the [_wp_enqueue_scripts()_](https://developer.wordpress.org/reference/functions/wp_enqueue_script/) function, which makes sense since we are adding scripts now.

The _wp_enqueue_scripts()_ function accepts the same parameters as _wp_enqueue_styles()_ except for the last one. For styles we pass the _$media_ parameter, but for scripts we pass the _$in_footer_ parameter. As you can gues when set to _true_ this parameter tells wordpress to put the script in the footer of the file.

*   **$in_footer:** Whether to enqueue the script before the _body_ tag instead of in the _head_. Defaults to ‘false’.

The code will now enqueue and output a new Javascript tag in the footer of your webpages like shown below:

{% gist https://gist.github.com/vanaf1979/4718086320cb2e8c6dee68b9f9c85938 %}

#### Remove a Javascript file:

In some cases it could be usefull te remove a script from the que simply becouse its not needed. For instance most WordPress themes enqueue the jQuery library. Now if you (or plugins) don’t need it it’s better for performance to just remove it from the page.

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/76ed5e9232bd0e9998f2ba1881937f2b) from line 6 below:

{% gist https://gist.github.com/vanaf1979/76ed5e9232bd0e9998f2ba1881937f2b %}

Here we call the [_wp_deregister_script()_](https://codex.wordpress.org/Function_Reference/wp_deregister_script) function and pass the handle for jquery. WordPress will now remove the jQuery library from the page.

#### Passing data from Php to Javascript:

Let’s say you have created a piece of Javascript that manipulates you webpage in such a way that it outputs a part of the interface. Great but what if part of that is some sort of text that you want to be translatable? Or what if that script depends on a path to your theme? That path could be changed by someone else!

WordPress has a way to pass data from Php to Javascript by using the [_wp_localize_script()_](https://codex.wordpress.org/Function_Reference/wp_localize_script). As it’s name implies this function is originally meant for passing translatable/localized strings, but it can very wel be used to pass other data like paths or theme versions.

Update the code in your _functions.php_ and add [the code](https://gist.github.com/vanaf1979/20ffe98a7ec8b454f7fad69edd88e865) from line 8 to 16 below:

{% gist https://gist.github.com/vanaf1979/20ffe98a7ec8b454f7fad69edd88e865 %}

Here instead of enueueing the script like we did before, wo now first register it using the [_wp_register_script()_](https://developer.wordpress.org/reference/functions/wp_register_script/) function. we then create a new array called $data_array which contains the data that we want to pass. It this case we pass two values:

*   **some_string:** Here we use the [WordPress I18N functionality](https://codex.wordpress.org/I18n_for_WordPress_Developers) to make a string translatable.
*   **themepath:** Here we pass a path to our theme from the [_get_template_directory_uri()_](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) function.

We then pass the _$data_array_ to the [_wp_localize_script()_](https://codex.wordpress.org/Function_Reference/wp_localize_script) function. _Wp_localize_script()_ accepts 3 paramaters:

*   **$handle:** The name of the script you are attaching the data to.
*   **$name:** The name of the variable/object which will contain the data in your Javascript. (This name has to be unique within your Javascript).
*   **$data:** The array of data you wish to pass to your Javascript.

Finaly we enqueue the script by using the _wp_enqueue_script()_ function again.

The code above will result in the following output in the footer of your webpagte:

{% gist https://gist.github.com/vanaf1979/99ec5bfd84f4bb7c6ca31208abbc5595 %}

You can now access the passed data in your Javascript like shown below.

{% gist https://gist.github.com/vanaf1979/a3bc8d028448ee736de2ab4ae0313426 %}

Here the object_name variable (Object) name comes from the _$name_ parameter passed to the _wp_locatize_script()_ function. And its members/values come from the _$data_array_ array we passed.

#### Changing the Link and Script tags:

Lately there has been [some debated](https://stackoverflow.com/questions/12634315/are-type-attributes-on-script-style-and-link-elements-still-needed) if the type attribute is really necessary on link and script tags. This is up to you but If you wish to remove them, or if you want to change your tags for some other reason like testing out the new [resource prioritization attributes](https://developers.google.com/web/fundamentals/performance/resource-prioritization), add the [following code](https://gist.github.com/vanaf1979/5fb59ecca45e2273e673fd24f168292d) to your _functions.php_.

{% gist https://gist.github.com/vanaf1979/5fb59ecca45e2273e673fd24f168292d %}

Before we used actions which let you **do** something, now we are going to use filters that let you **change** something. In this case we need to change the _link_ and _script_ tags so we use the _add_filter()_ function here.

The [_add_filter_()](https://developer.wordpress.org/reference/functions/add_filter/) function takes 4 parameters, like the _add_action()_ function:

*   **$tag:** The name of the action to which the callback function is hooked.
*   **$function_to_add:** The name of the callback function you wish to be called.
*   **$priority:** Used to specify the order in which the functions associated with a particular action are executed.
*   **$accepted_args:** The number of arguments the callback function accepts.

In the code above we add two filter hooks with the _add_filters()_ function. But this time we do pass the last two parameters because we need the callback to accept more parameters. so in this case we set _$priority_ to 10 and the _$accepted_args_ to 4 for the _style_loader_tag_ hook and to 3 for the _script_loader_tag_ hook. Again more on this can be found in [this article](https://docs.presscustomizr.com/article/26-wordpress-actions-filters-and-hooks-a-guide-for-non-developers).

The _my_theme_optimize_style_tags()_ callback function is now called for each Css stylesheet that has been enqueued and recieves 4 paramters since we set the _$accepted_args_ to 4:

*   **$html:** The complete html for the link tag.
*   **$handle:** The handle/name of the stylesheet.
*   **$href:** The Url/Path to the stylesheet.
*   **$media:** The mediatype for this stylesheet.

Within this function we need to return the changed/filtered value of the _$html_ parameter but we simply return an new string containing the link tag, as we want it to be output by WordPress, using the passed in parameters with php string enterpalation.

The _my_theme_optimize_script_tags()_ callback function is now called for each Javascript file that has been enqueued and recieves 3 paramters since we set the _$accepted_args_ to 3:

*   **$tag:** The complete html for the script tag.
*   **$handle:** The handle/name of the stylesheet.
*   **$src:** The Url/Path to the stylesheet.

Again we need to return the changed value of _$tag_ but we return an new string containing the script tag, as we want it to be output by WordPress.

The code above changes the output to the following into your webpage.

{% gist https://gist.github.com/vanaf1979/7af1e527bfddb31a7313caf3ceec7dd8 %}

Note that the inline styles still have the _type=”text/css”_ attribute. I still have to find a solution to this. If you know of any please let me know so i can add it to this article.

#### Async/defer your Javascripts:

Async and defer are relatively new atrtributes to the script tags. You can read all about [defer here](https://www.w3schools.com/tags/att_script_defer.asp) and [async here](https://www.w3schools.com/tags/att_script_async.asp). To add these to your script tags we need to change [the code](https://gist.github.com/vanaf1979/67abaa17998dbddd6f0830d3f7048ffb) off the _my_theme_optimize_script_tag()_ function from earlier as shown below.

{% gist https://gist.github.com/vanaf1979/67abaa17998dbddd6f0830d3f7048ffb %}

Here we check the _$handle_ parameter to see if this is the correct script because we likely dont want to async defer all javascript files. If _true_ we pass the string “async defer” to the _$defer_ vaiable, if _false_ we pass an empty string.

We then add the content of the $defer vanriable to the returned script tag.

The code change above adds the defer and async atributed to the _my-theme-scripts_ script tag like shown below:

{% gist https://gist.github.com/vanaf1979/b9830d47e69c1a1cfdca449a9af5f1fa %}

### Use wp_get_theme:

To make your _functions.php_ file a bit more maintainable I advise you to make use of the [_wp_get_theme()_](https://codex.wordpress.org/Function_Reference/wp_get_theme) functionality. This function returns a [_WP_Theme_](https://codex.wordpress.org/Class_Reference/WP_Theme) class instance containing the Name, ThemeURI, Description, Author, AuthorURI, Version, Template, Status, Tags, TextDomain and DomainPath of the current theme as private properties.

The returned class instance also contains a _get()_ method which can be used to get the values mentioned above from the object. As an example you can use [this code](https://gist.github.com/vanaf1979/2669916bd47970982db3853daedabce1) to prefix your handles and pass the theme version to your _wp_enqueue_style()_ and _wp_enqueue_script()_ functions as shown below:

{% gist https://gist.github.com/vanaf1979/2669916bd47970982db3853daedabce1 %}

Now when you change your theme name or theme version this will automaticaly be reflected within the output of Link and Script tags.

#### Completed code:

Below you find [the completed code](https://gist.github.com/vanaf1979/47e63bbc9940983e911ef50668524d0f) which you can use as a boilerplate for your _functions.php_ file.

{% gist https://gist.github.com/vanaf1979/47e63bbc9940983e911ef50668524d0f %}

#### Tip: FunctionsPhp

As your theme grows in complexity so does your functions.php file and it can quickly become hard to maintain. For that reason i created [FunctionsPhp](https://github.com/vanaf1979/functionsphp): A Maintainable OOP WordPress functions.php boilerplate. Check it out on [GitHub](https://github.com/vanaf1979/functionsphp).

#### Suggestions!?

I hope you liked this tutorial and found something usefull. If you have any questions or suggestions please get in touch via Twitter: [Vanaf1979](http://bit.ly/2RCf9eF), [my website Since1979.dev](https://since1979.dev) or comment here on Dev.