WordPress People, Please Enqueue Your Scripts

Or more simply, “How to Include Scripts in WordPress.”

It’s a problem I see far too often. People like to include their scripts in header.php or index.php or some other template file. Please do not do this.

It’s easy, for sure. But it’s horrible for making changes to. If you put some javascript in the template, WordPress won’t know it exists. What does this mean? Well in practice it often means things like jQuery being imported twice. And libraries like jQuery are often downloaded from CDNs, if you have one grab from Google CDN, and one from MaxCDN or your own host, then it will be downloaded twice. Or what if the versions don’t match. WordPress is a Content Management System. Let it manage.

wp_enqueue_scripts is not all that difficult to work with. I’ll admit, every time I use it I first look it up in the codex, but that only takes a few seconds. Here’s what I see:

The handle is the name WordPress will remember it as. Sometimes the handle is all you need. If you wanted to include jQuery, for example, and you wanted to get it from your WordPress instance, just use

 

. WordPress already knows where to find it and will put the code in for you. If you are adding your own script you can put any name here you want. I often come up with something like ‘stp_Animations’, I like to stick my initials in there to make sure it doesn’t conflict with any other script names.

The src is exactly what you might guess, a string of the url of where to find your script. The trick here is to refer to the right folder. You don’t want to hard code an address, so you will want to use one of three functions to get the first part of the address. plugins_url(), get_template_directory(), get_stylesheet_directory() are your friends here.

deps is the most important part here. I see it as the main reason to use wp_enqueue_script. It can sometimes be tricky to get WordPress to include your script in the order that you choose, there is no guarantee here. But the reality is, you don’t usually care what order WordPress includes your script in, do you? You only care if your script depends on another script. So if I enqueue my script wp_enqueue_script( ‘myscript’ , ‘http://steve.thomaspatel.com/js/myscript.js’, array( ‘jquery’ ) ), I don’t know when the script will be inserted, but I do know it will come after jQuery. And the reason that parameter is an array is because I can have multiple dependencies.

ver keeps track of version numbers if you are versioning your scripts. When I am enqueueing my own scripts this doesn’t usually matter to me, I’ll put a 1.0 or a 0.0.1 is often a favorite of mine. And finally there is in_footer. In general it is good practice to have your scripts loaded last, after everything else on the page has been rendered your scripts are allowed to enter the picture.

And I almost forgot to mention one of the most useful reasons for this method. Whether you use a plugin specifically to minify your js, or if you use a broader site speeder upper like W3 Total Cache, the good ones like to combine your scripts into one file. This sometimes drastically speeds up download times because it requires fewer connections with the host, and less negotiation. But how is the plugin supposed to know where to find your scripts? Or how to remove them before inserting the combined script? It has to ask WordPress, and WordPress only knows if you have enqueued your script correctly.

Django, Permalinks and The Onion

Here’s something a little baddass from The Onion. It strikes me as a bit daring, and out-of-the-box in thinking. (Who knew their developers were as creative as their writers?) To see what I’m talking about, try this before you read on. Go to theonion.com. Click on a link to an article, any article. Look at the URL, I’ll use this one from today as an example:

http://www.theonion.com/articles/health-experts-recommend-standing-up-at-desk-leavi,37957/

The part of the url we are interested in is between the second to last forward slash and before the comma.

Take all of those words and delete them. Replace them with a letter, or a word, you have to have something there but it doesn’t really matter what. Just leave the comma and the number. What do you notice?

I learned about it from this wellfire blog.

What The Onion did was create a permalink structure that ignores the article name itself and only looks at the number, the ID of the article. This is brilliant because a search engine and human eyes are going to look to the words. They have SEO value. But the number is what The Onion’s web server (which runs on Python and Django), uses to look up the article. It is the ID of the article, which in Database time is essentially instant look up time. Compare this to WordPress which has a whole stack of lookups it has to perform before coming up with your article, as it has to disambiguate whether you are providing say, a category, or a tag, a page id or a slug.

The other thing I found interesting was that when you delete words from the url, you get redirected to the correct url. This protects the consistency of the url discouraging people from linking incorrectly across the web to these articles, and it protects from the risk of a search engine seeing a particular site of existing in a thousand (or infinite) number of locations.

So I’m pushing forward with Django. I’ve had some discouraging moments, as I’ve made a lot of rapid progress but as I look forward into what I still have to learn, it is starting to look like a mountain rather than a large hill. Yesterday I played around with Django CMS which is a neat tool for building websites rapidly and has a neat structure for plugging in apps. It’s also helping me to really dissect Django and helping me to understand its power. Sticking with the mountain climbing analogy, it’s like somebody left a helicopter lying around about halfway up the thing with the keys in the ignition (is that how helicopters work?). I can use the helicopter to view my climb better, but it will tempt me to bypass my climb altogether if I’m not careful.

Exploring Django

I’ve been getting really tired lately of the weight of WordPress websites. The more time I spend with WordPress, the more I appreciate the features it provides, from versioning, to the plugin system that works so well. While it’s not as simple as just install it and go for most people, anyone can learn to use it. But I just find, particularly the admin areas, such a pain to work with. Requests can be so slow. The simpler the task you want to complete, the more grueling the wait. So I started exploring other alternatives.Read More

WordPress Sites Being Attacked – How to Protect Yours

A widespread attack is going on around the internet, looking for and compromising WordPress based websites. The attack method is fairly unsophisticated, but is quite powerful because of its breadth. Protecting your site against this attack is not particularly difficult, although that might change if it becomes more sophisticated.

The method of attack attempts to log in to WordPress using the username “admin”. The machines doing this assume that the username “admin” exists and then perform a “dictionary attack” which just means trying all sorts of passwords from a very large index of possible passwords until it finds one that works. The dictionary here is not the actual dictionary, but a metaphorical one that includes all real words, plus many variations and combinations with numbers and symbols thrown in as well. Dictionary attacks are very basic, but also very effective and they are the reason it is so important to use good, strong passwords.

Once a person is able to log into WordPress as an administrator they have full powers and privileges and can use the machine that hosts your website do pretty much anything they want it to do, such as to turn around and attack someone else’s machine. One thing that is known about these attacks is that they come from over 90,000 ip addresses which could mean they have compromised that many websites.

So what’s the solution?Read More

Sudoku preview

The solver for the Sudoku game was a fun challenge.

At it base, the solver is a brute force, recursive algorithm. But the most simple version is O(n^n), which is obviously not acceptable for a 9×9 table. There are a few optimizations that rescue it though.

The first is obvious, start by eliminating possibilities across the horizontals, verticals and blocks anything that conflicts with initial values.

The second trick is really neat. Instead of walking through the Sudoku board left to right, top to bottom fashion, or whatever arbitrary pattern you might come up with, you start with the square with the fewest remaining possibilities, then go to the next lowest and next lowest and so on. This was your tree has the fewest branches at the top and the most at the bottom, you end up with many, many fewer test solutions to try out.

I wish I could take credit for that solution, but I had to search for it and found it here.

For now, it shows off some basic programming skills in JavaScript, mainly Object Programming and general familiarity with the language, as well as manipulating the DOM with jQuery.

The next thing I would like to do with it is to offer a more beautiful html5 canvas ui and work in some animation. I’ve also been thinking about writing the board library in php, or putting it in a database and loading it in using ajax.

My Sudoku Game

Java Security Issue

The U.S. Department of Homeland Security issued a recommendation that everyone who can, should disable Java (not Javascript, which I wish people would not disable).

It’s an interesting story because it is only the second time the DHS has asked people to remove/disable software. The previous time being a version of Microsoft Internet Explorer (big surprise, right?), until it was fixed. Java has a long storied history which I went over a little in my post Why So Many Programming Languages?. It seems most people who use Java aren’t aware they are using it.

It’s relatively rare to come across a website that requires Java. I’ve run into it the most when a video wanted to play and Chrome asked me if I wanted to give it permission. I don’t know why anyone is using Java for this purpose when there are so many lighter alternatives available. For the time being, if you run across one of these the prudent thing to do would be to deny the website permission because even though you may trust the website you are visiting, you can’t know if they have been compromised.

What I’m interested in with this mess is, what it will do to the Java brand? Until today, many people were unaware they were using Java at all, so now they are being hit with this message of the Department of Homeland Security says your computer may be vulnerable because of a piece of software called Java that you didn’t even know you were running, and we don’t have a fix for it yet.

Despite once being on the brink of extinction when it failed to take hold in the browser, Java is still important. If you have an Android or a Blackberry phone, you use it everyday- all of your apps are built on it. But as far as I can tell from what I am reading, you’re probably pretty safe. I don’t know the technical details on this particular vulnerability, but Android apps run in a very tightly secured environment (each runs as it’s own linux “user” under the Android operating system), so it’s likely they would be stopped before doing anything too destructive.

Update: Oracle has posted what they are calling a “fix” to the Java problem, but security experts are skeptical. ZDNet says it will be about two years before Oracle gets the security issues solved. My prediction is this will be the end of Java in the desktop browser. My new questions is, will we soon be calling the unrelated language, JavaScript, by it’s more technically accurate, but clumsier name “ECMAScript”?

The Sudoku Challenge

I’ve challenged myself to create a game of Sudoku. Why you ask? Because it is broad enough to exercise all of the different Javascript skills I want to work on, while not being so complex as to be a big time sink on any one area.

In computer programming, it is not often the case that the challenge you end up with is the same as you conceived beforehand. Three days into it, I’m happy to say it is exactly as I had hoped for.

The Sudoku puzzle, like most web apps, breaks apart nicely into the MVC model. I wrote the model first and it was pretty easy. I made a two dimensional array to represent the squares, and a square object to fill each square. I hit a major snag when my outputs showed everything as working as it should, but then when I tried to output the board all at once, every square was filled with the value of the last square! It turned out at that point I didn’t understand closures as well as I thought I did, and instead of creating the 81 squares of the sudoku board, I was creating only one and changing it’s value. It was a pain to debug, but I came out of it really understanding Javascript closures.Read More

Another take on Panoramas

Here’s another solution for panoramas. It’s actually a 360 degree pan viewer, one of those virtual world things that are about as old as interactivity on the world wide web. But the person (Audrey Scott) using it is a travel photographer and her goal is to present a beautiful photograph of the pyramid at the Louvre. The solution has it’s problems, but I’m taking it into account as I think about my lightbox project.

My immediate question is, Is it Photography?

Technically, yes. It uses a cameraRead More

WordPress Recipe Plugin

Want a simple, easy to use and fully customizable recipe plugin for WordPress? I spent a few hours today putting it together. Although it’s still in early beta, I’m pretty happy about it. It features a custom recipe post type, categories and tags that are specifically for your recipes rather than for all of your posts together, and shortcodes to include the recipes in your posts.

We’ve been using a different plugin at Indiaphile for our recipes and it just wasn’t working out well. You could only have one recipe per post, and you were completely restricted to that plugin’s formatting. This one is completely open, it uses shortcodes to describe what certain information is, such as [ingredients]your ingredients here (separated by line breaks)[/ingredients]. This gives you complete freedom to add in additional notes and information that doesn’t necessarily fit into someone else’s rigid formatting.

It is definitely in a workable state, but there are other features on the way, such as custom formatting options and a shortcode generator. As it is now, you can format the recipes with your own custom css as the whole thing is wrapped in a div.stp_recipe

I just used it to convert the recipes in an old post at indiaphile: Tandoori Paneer Pizza. That was so easy!

You can download the plugin here. Remember, this is an early development release, you’ll either have to understand the code or have to talk to me about how to use it. But trust me, it’s pretty darn simple and powerful if you know how it works!

Screenshots:
Read More