Build Your Own Business Website header image

Advanced Thesis 2.1 Box Development – Part 3 – Adding Scripts and Styles to the Box

Difficulty Level -

Filed Under Topics -

Listed Under Lesson Subjects -

Applies to -

Whoops, you've found some premium content!

Watch the opening clip of this video to preview it,
the full video is available to paid members.

Now that we’ve got the base Thesis 2.1 box set up with its folders and files, the first real thing we have to do is to add these scripts and styles you see here correctly to WordPress.

Enqueue Scripts and Styles

There have been and still are a ton of very poor tutorials out there that tell you to do this by adding an action to the head of your page and then just echoing scripts like this to it.

Well, the problem is that if you are calling one here that is already being called some place else especially with things like jQuery then you run the risk of having two copies of jQuery being installed which almost always a breaks jQuery. To fix this WordPress several years ago came up with this concept of enqueue scripts and enqueue styles.

How Browsers Load Files

Another aspect of that is that the way a web page loads files. CSS files can be loaded simultaneously so when CSS files are found by your browser in the head of the document, it can download one CSS file and immediately begin downloading the other one at the same time. Then another one and another one and so on without having to stop loading. However, javascript files are different.

Issue: Javascript Loads Synchronously

As soon as you get to a javascript file, loading stops. It has to load that entire javascript file and then go on to the next entire javascript file and then go on to the next entire javascript file. So javascript is loaded synchronously which means that you can’t load one until you’ve loaded the one before it.

Now, this is one of the reasons why everybody wants you to add your javascript to the bottom of your page. That way the page continues to load without slowing the site down. The page continues to load even though the javascript file isn’t loaded.

So in WordPress you would never load it like this. You would never load a javascript and then a javascript and then a stylesheet and then a stylesheet and then a javascript because these stylesheets can’t be loaded until these javascripts are loaded individually. So what you would do then is take the stylesheets and put them in front.

Enqueue Scripts Solve the Loading Issue

But enqueue scripts solve the loading issue for you because if you’re using the enqueue style then WordPress will load all the stylesheets together at the top and then begin loading javascript either at the bottom of the page or at the top of the page depending upon the instruction that it’s given.

If more than one plugin theme box skin calls the same file, call jQuery or modernizr or whatever, then it will only load it once. It won’t try to load it more than once and this is critical, this is a mistake that beginning programmers make regularly but it is absolutely critical to the proper functioning of WordPress.

I was working on a client site and the owner had this high priced consultant helping him work on customer engagement. Ordinarily they do all the WordPress management for their customers but because I’ve done all the work on his site I’m doing the implementation of that for them.

When their developers sent me over PHP files that load this javascript they were entirely incorrect and would’ve just destroyed the site. This person was a lead WordPress developer on the business card but they were still going to load javascript in a way that would’ve killed the site.

That’s why I’m emphasizing this concept. The only way to add CSS and javascript to WordPress is using enqueue styes and enqueue scripts.

Create the Enqueue Scripts

To start off we’re going to create a new function. We’ll call it public function add_scripts and we’ll just copy that public function add_styles. So we’ve got two functions here that will be used for calling scripts and calling styles.

Functions of wp_enqueue_script and wp_wp_enqueue_scripts

Let’s start with the scripts one, wp_enqueue_script. So there are two different functions – one is wp_enqueue_script and the other wp_enqueue_scripts. The wp_enqueue_script is the one where you add a specific script to WordPress whereas the wp_enqueue_scripts is the hook that you hook your function that has wp_enqueue_script in it.

So if it’s got “s” after it, it’s the hook and if it doesn’t have any “s” then it’s the function. I’m just going to copy wp_enqueue_script, come over to our file and paste that.

Create the First Script

You have to give your script a handle. Well, these are the parts actually – the handle, the source, whatever scripts it may be dependent upon, the version if it has a version and whether or not it’s in the footer.

The Handle

WordPress has a whole bunch of established handles already, that is scripts that WordPress already has available. And all you have to do is wp_enqueue_script $handle and you don’t need any of the other code because it already knows what it needs and where it is. But because these are custom made we’re going to have to do this ourselves.

The first one they load and often the order in which things are loaded is very important. They’re loading jQuery first but we’re going to load custom.modernizr first for reasons you’ll see in a moment. I’m going to give it its own handle ‘cust_mod’ for custom.modernizr.

Dependents

Now, the src they give you in this file is this js/custom.modernizr.js. Dependents are the scripts that it requires to have loaded first. Because the instructions say to load jQuery first we’re going to make jQuery a dependent. You don’t actually have to load it because all we have to do is make it a dependent and WordPress will load it for us in the appropriate location.

You refer to your dependents by their handles so the WordPress handle for jQuery is as you might guess, ‘jquery’. The way this works is a ‘dependents’ expects an array of stuff. So even if it just requires jQuery you still need to put it inside of an array, so array(‘jquery’).

If you want to know what the other scripts are that WordPress can automatically load for you on this wp_enqueue_script section, you can see all of the names here. For example, Image Cropper, Jcrop, SWFObject, jQuery, these are the script names and these are the handles that are being used.

If one of these handles has a dependent you don’t actually have to specify it because it already knows that jquery-ui-draggable requires jquery. So if you call it jquery-ui-sortable it’ll automatically call jquery first and there’s just all kinds of these things that you can do.

For example jQuery Masonry is in here some place. jQuery MediaElement is in here, ColorPicker or Farbtastic are a couple of different versions of color pickers. These are all kinds of javascript libraries that are included in the core of WordPress that you can simply call while using your handle.

$in_footer

Back to our code. We’re not going to give a version so we’ll just leave that as an empty space. Then $in_footer takes true or false, I’m going to say true. Note that true is not in parenthesis that’s because true is abelian which means it’s either true or false. Those are abelian values and as such they do not need to be contained inside of single quotes like this.

We’ll talk about data types here in a few minutes because we’re going to see another good example of this.

Create Second Script

So that’s one script and we’ll come along here to the next script which is going to be jquery.unleash.3.js. So come back over here and instead of ‘cust_mod’ we’ll say ‘unleash3’ and then replace this src with that.

Then in this case, it’s ‘jquery’ and ‘cust_mod’. We don’t know for sure that the order absolutely matters but we’re assuming it matters because of the way he’s organized it so we’re just going to play it safe.

Create the Enqueue Style

Now we have the two scripts enqueued and the next thing we want to do is enqueue the style. Well, enqueue style works very much the same way, so wp_enqueue_style. Again, it takes a handle and src, dependents if there are any, version if there is one and then what media query you want this to apply to.

Let’s copy this and the handle for the style we’ll call ‘cust_animate’ because I don’t want to run into the possibility of another one not working if somebody else is using ‘animate’ as a handle.

Then we’ll come back and look what at src and it uses this ‘/css/animate.css’. It doesn’t have any dependents, it doesn’t have a version and it’s going to be used in all media so we can actually just delete these because those are all optional.

Create a File Constant for Relative URL

So we’ve enqueued the style called ‘cust_animate’, ‘/css/animate.css’. But there’s a problem with this src and that is that this is relative and unfortunately, relative src’s like this do not work well. So what we have to do is create a file constant and use that to create a relative URL. Now we’re going to do that in the construct method, so protected function construct.

If you’re familiar with object oriented programming for PHP you know that there is a magic method called “construct” and that starts with an underscore (_) like this. However, this is not that magic method, this is essentially an alias to it that Thesis uses.

Thesis looks for this method name “construct” and then treats it as if it’s the magic constructive method. If you’re not familiar with that it doesn’t matter, just know it’s “construct” without the underscore (_).

But know that that’s only the case in Thesis boxes and Thesis skins. It doesn’t have anything to do really with the typical way in which object oriented PHP uses the constructive method.

So we have our protected function construct. This gets called on every page load so you want to be careful about the code that you put in it. Anything that you are doing that initializes the plugin, any kind of initialization stuff has to go inside the construct here.

Define the File Constant

So what we’re going to do then is to define a file constant and we use this define($name, $value). Our $name is going to be ‘BYOBUAS_URL’ and then the $value in this case, we’re going to use a Thesis file constant.

Thesis has a number of file constants. The one that we are using here at the moment is THESIS. When you are creating a constant the name of the constant is all uppercase so THESIS_USER_BOXES_URL.

This generates the URL version of the address. In this case, the URL version of the address for the THESIS_USER_BOXES_URL which in our case is wp-content/thesis/boxes. That’s what THESIS_USER_BOXES_URL refers to and then we put a concatenation symbol in and then the rest of the path to this box.

Let’s put a semicolon here first and then the rest of the path to the box is slash (/) and then it’s this name here. We’re going to copy it. And we have now created a definition of the URL that is called ‘BYOBUAS_URL’.

Absolute URL vs http URL

You may have some experience with me talking about file constants. There are two different ways every file in your website can be referenced.

One of them is the absolute URL or what can also be called the local path URL. That is the address of a file that would be used by other files on the server. So if you need a file to be available to PHP then you would use the local path to get to it.

However, we need these files to be available to the web browser and so the web browser cannot use the local path address. It needs to use the http URL and so we are calling the URL version of the address of the file. I don’t think we’re going to use any local paths in this class but anytime you’re calling the CSS file or a javascript file you need to use the URL version of the address.

So what we’ve done here with this definition is we’ve created it and now what we can do is put it in front of that with a concatenation symbol. This stands in for http://www.thesis2demo.com/wp-content/thesis/boxes and we need to add our opening slash to these because we’ve defined this without the slash.

This is the normal WordPress way of doing it. That is to add the slash to these absolute and relative URLs not to the definition of the constant but to the remaining file path like that.

How to Prevent Double Definitions

So now we’re saying here’s the CSS location, here’s those two locations. We’re partly there, we’re not all the way there. The other thing is that the most recent version of PHP, PHP 5.4 will issue a notice when it finds something having been defined twice.

While this doesn’t really happen very often, it’s going to happen with boxes because you may have more than one instance of the box and so what you have to do here is in advance of this, you have to add an if statement, if(!defined()).

We’re saying if this is not defined then define it. So if this has already been defined it won’t be defined again and you won’t get an error notice saying that there’s a problem. Now, you only see error notices if you turn on wp_debug in your wp-config file but nevertheless, best practice is to make sure that you don’t create any notices. And you wouldn’t get the notice in PHP 5.2 or 5.3 but you will in PHP 5.4 so you may as well just do it this way.

Load Javascript and CSS Only When Necessary

The next thing to do is add these methods, the scripts and styles, to our site yet. We’ve created the methods but we haven’t added them and so nothing is actually happening with these. This wp_enqueue_script is not actually firing because we haven’t added this function to the wp_enqueue_scripts hook.

You could do it here under construct. The problem with that is, is that every single page then is going to have these CSS files and these javascript files added to them but fortunately, Thesis gives us a way of avoiding.

Use the Thesis Public Function

Most plugins load all their javascript and CSS on every page load regardless of whether it’s needed and that’s very poor practice but most of them still do it. We’re not going to do that. We’re going to use the tool that Thesis has given us to load this stuff only when it’s necessary and that is called public function and preload.

This gets called only when the box is actually on a page so any place that doesn’t have the Accordian Slider on it will not get this code added to it. That is the best practice.

Richard said, “Isn’t a trailing slash required after byob_unleash_slider?” No, you don’t need the trailing slash there because we’re putting the opening slash there. This is the way WordPress works. You can choose one way or the other.

But what this does is this identifies the folder without identifying anything inside the folder and this identifies the stuff inside the folder, so we’re using WordPress convention. Actually, it doesn’t matter which way you do it really except this is the WordPress convention for doing it.

Add the Scripts and Styles to the Public Function

So public function preload and now we can add our scripts and add our styles to the appropriate hook. And the appropriate hook is wp_enqueue_scripts for both of these. So now we are going to have our add_action because this is an action hook and the action is (‘wp_enqueue_scripts’).

That’s the name of the hook and then we put the name of our function that we want to add there which is add_scripts. Now the way you add a method inside of a class to regular WordPress hooks is by saying array($this, add_scripts()).

If you were just using regular old PHP you would add_action, the hook name and then the function name but because we are using object oriented programming and you can’t just use the function name, you have to specify this.

That’s what it looks like right there, $this, ‘add_scripts’. So the function name is in an array where this is the first part of the array and the function name is the second part so that’s adding adding our scripts.

We do exactly the same thing for styles, add_action(‘wp_enqueue_scripts’ but this time we’re using the ‘add_styles’ method. Hit save to that.

Check File Loading

Now we’re going to upload this box and see whether or not it actually shows up. That is, we’ll see whether or not our CSS files and javascript files actually get loaded. Let’s just refresh this and then the name of this thing was byob-unleash3-accordian-slider, here it is.

I missed changing the pasted name to the styles. I think I’m okay here. Yes, that’s the way it works, ‘add_scripts’, ‘add_styles’. This is the same action hook wp_enqueue_scripts, for both of them so I think we’re fine there. Let’s upload it now and come back over to our site.

Add the BYOB Accordion Slider Box to the Site

Refresh this box and here it is, BYOB Unleash 3 Accordion Slider. I’m going to check it and hit Save Boxes. Then I’m going to come on over to the Skin Editor and we’ll just do it on Home since it’s easy to get to.

Come over here and see if it’s down here. Yes, BYOB Accordion Slider has been added to the list. If we shift+drag that in and drop it into Content Area Page. Right now it can’t do anything. We’re not asking it to do anything it’s just there.

Let’s save this template and view the site. We should find that our javascript and CSS files are being loaded so let’s check that. Yes, here it is. The CSS files would be in the head and we have our

Here’s the CSS. When we click on that we should see it and it is there. So we’ve got that file added and then if we come back to our elements and scroll down to the bottom we’ve got animate.css, that’s the head. Let’s look in the body now and at the bottom of the body we’ve got admin.bar, unleash3-accordion-slider/js/ and the jQuery in the correct order. There it is.

If we go to a regular page and look for that we’re going to see that it’s not in the head, that CSS file

0 Comments… add one
0 comments… add one

Leave a Comment