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

Book Review: Bossypants by Tina Fey

To preface I’m not a Tina Fey fan. I don’t mean that in the way that means I dislike her work. I just never locked in to all of that hype around her.

I think that’s a plus when you read a book like Bossypants. The only better position to be in might be to not even know who the person is. A real fan is already going to love the book before they’ve even opened it. I guess I’m just saying all of this to make the point that I am not that person.

I actually picked up the book expecting the traditional comedian’s book of one liners and jokey anecdotes. I’ve read a few of those over the years, from Seinfeld to Woody Allen to Drew Carey. But Fey’s book was something completely different. Hers had weight, the kind of weight that just kind of sneeks up on you so you don’t even have notice it if you don’t want to. I haven’t read Sheryl Sandberg’s Lean In, but that couldn’t prevent me from thinking repeatedly, this is the book she should have written. Obviously I can’t back that statement up, for all I know, Lean In is exactly the book Sheryl Sandberg should have written, but I still couldn’t shake the feeling.

It’s easy to forget comics of her caliber have to navigate the same cutthroat corporate shark infested waters that people who take the Sandberg path have to. They combat the same barriers, working with people who run interference because of ego or personal ambition, they fight the same battles of sexism and discrimination, of higher ups who don’t seem to have a clue about the troops on the ground. But creatives often do it in a way they make look fun and effortless, with an apparent Mr. Bean-like brilliant oblivion, appearing to scale the barriers effortlessly. The difference is, as friends and foes slip to their dooms, the ones we outsiders pay attention to are the ones who through luck, skill and determination keep their grip and keep climbing.

One reason I never became a fan of Tina Fey’s is because I couldn’t get interested in 30 Rock the couple of times I tuned in. Tina Fey describes the difficulty the writers have had with the show. It’s been a darling to critics yet never really caught on with the mainstream. Everyone seems to know the show but nobody seems to watch it. I think the problem is with the pace. Sometimes it’s just too quick-witted to follow along. To really get it, you have to pay attention. A tough sell in today’s ADD world. I think most of us approach new shows with skepticism, prove you are worthy of my attention and you might get some. After I read her book I started watching on Netflix from the pilot on. I get it now.

Cripple Creek on Guitar

I’ve been learning a lot on my guitar lately and I was playing around and recorded Cripple Creek, an old bluegrass song. Today I discovered SoundCloud and decided to put it up. I’m thinking about using it to chart my progress. In the meantime, enjoy!

(By default it was going to put my facebook picture next to the player, so I almost randomly picked that one of the rock, doesn’t really apply to anything)

Trying Out Google’s New Music Service And a Renewed Appreciation for Bob Dylan

Those who know me personally or who follow me on social media are probably aware of my recent interest in Bluegrass music. I started going to weekly jams at “Today’s Pizza & Salad” in Encinitas. It’s a bit of a drive for me but it’s worth it.

Naturally the group plays a lot of the same songs, although last night was pretty different. Among the repertoire two songs have stood out to me. One being “You Ain’t Going Nowhere”, the other “Wagon Wheel.” It turns out the writing credit for both of these songs belongs to Bob Dylan, but neither were originally commercially released by him. “You Ain’t Going Nowhere” was first sold as a Byrds song, although Dylan had already done a recording of it, he did not release his version for another 3 years. “Wagon Wheel” has an even stranger story, because Dylan didn’t release it, or even finish it at all. The Old Crow Medicine Show heard a sketch of this song Dylan had started on a bootleg and decided to finish and record it, thirty years after Dylan apparently gave up on it.

Reading about all of that, especially the Wagon Wheel thing, just got me thinking on how tremendous of an impact this one guy had on the history of American music. Even a song he once threw away became a hit. I’ve always had an appreciation for Bob Dylan, especially his more classic albums like “Blonde on Blonde,” but when you lay out a list of his work it’s truly amazing. Here’s just a short list of his greatest songs that I threw together (therefore I’m undoubtedly missing some obvious ones), I’ll put some covers in brackets:

  • One More Cup of Coffee [The White Stripes]
  • Tambourine Man [The Byrds]
  • Like a Rolling Stone
  • All Along the Watchtower [Jimi Hendrix]
  • Maggie’s Farm [Rage Against the Machine]
  • Girl From the North Country
  • Lay Lady Lay
  • Don’t Think Twice It’s Alright
  • Blowing in the Wind
  • Masters of War
  • Forever Young
  • Just Like a Woman
  • You Ain’t Goin’ Nowhere [The Byrds, Nitty Gritty Dirt Band]
  • Knockin on Heaven’s Door [Guns ‘n Roses]
  • The Time’s They Are a Changing
  • It’s Alright Ma (I’m Only Bleeding)
  • Wagon Wheel [Old Crow Medicine Show]

Google just launched a music service (May 15th), and they are offering a 30-day free trial as well as a discounted price to anyone who signs up before May 30th. So I jumped on it. This couldn’t have happened at a better time since I’ve been going crazy at the library checking out bluegrass cds to try to soak up as much about the genre as I can. I love the service. It’s supposed to be an answer to Spotify. It seems to offer about the same service as the premium plan for spotify for a couple of dollars less, but I haven’t explored Spotify so I can’t really compare.

So far I’m really liking it. I haven’t come across any missing artists, just a few missing albums. Of course I don’t listen to I have a few issues with the usability of it. I haven’t quite figured out how to control what songs go on my cell phone. The first day I streamed a bunch of music and used about 250mb, which is unacceptable with my data plan, so getting this download thing figured out is going to be the deal breaker after the 30 day trial is up.

Okay, I just did a test I knew expected to fail. I found a major artist who isn’t on there, Tool. On the plus side, there are a lot of comedy albums on there, I can finally hear these albums Marc Maron keeps referring to on WTF.

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

Post PC World?

Google recently announced a new parting of ways with Apple on an open source project controlled by Apple called WebKit. WebKit is the rendering part of a web browser, the piece that reads all of the code behind a web page and draws it on your screen. As you can imagine, this is a pretty massive piece of the web browser. A massive piece that was shared by Apple’s Safari, Google’s Chrome (and Chromium) as well as other browsers such as Opera, and perhaps most significantly, browsers found in devices from Kindle to Blackberry.

Google will now fork WebKit, spawning a version they control called Blink.

“Having multiple rendering engines will no doubt lead to more innovation,” says Adrian Kingsley-Hughes at ZDNet. But “The reason Google wants Blink is down to one thing — the post-PC era.” (source)

One thing Google has said about this project is that it will remove millions of lines of code from WebKit. Blink will be smaller and ostensibly more efficient than WebKit. Google’s goal is to make it run faster and with a smaller footprint for the purpose of tablets and other devices.

This concerns me for two reasons. 1. Google is making a heavy investments in the idea that the PC is going away. 2. Google does not predict the computing power of tablets in the near future will approach that of PCs.

In other words we will be sacrificing the computing power of a PC for the convenience of handheld devices. Our devices will no longer augment our PCs but replace them.

It’s a prediction that has been around for a long while, no doubt many people would say no kidding. But to me it’s a sad day. PCs are vastly different than tablets in the openness and power they provide to the user. Where PCs strive to be general and useful, to be a tool in our exploration of the world about us, devices are about convenience, attempting to solve our problems for us even before we know that we have them. PCs can be ripped apart, upgraded, replaced piece by piece. Devices now seal in the battery. The battery. Devices are of a world in which we have to throw out the lamp when the bulb burns out.

My first operating system was DOS. I used to write batch files to get things to work the way I wanted them to. Networking was fickle and as a kid I had to jigger and hack software to play the games I wanted to play. Working with the file system meant typing commands (dir, tree, mkdir, rmdir, erase, format, ok my memory is failing me here, some of those may only be the linux commands). When a hard drive went bad, or a video card, I replaced it. It was a valuable learning experience without even having the intention at the time to learn, I just wanted to play. The things I learned as a kid shaped the way I understood and approached computers through the years. By the time I was taking Computer Science courses, I already had a very solid understanding of the inner-workings of computers. I believe most of my peers did as well. I have a hard time seeing how a child today would build a foundation like that from these devices given their closed in nature.

But more selfishly and practically, I worry about trade-off between portability and power. I sometimes sit in awe at all of the things I do at the computer. Not at myself and my work, but at the ability of this one machine in front of me that gives me the power to do all of these things. To edit photos with more power than an entire darkroom once gave a photographer. To edit video, music. To have a movie or TV show streaming on the other monitor as I work on these things.

Or am I’m just an old man who doesn’t understand the new world and dislikes the new thing? The future will tell.

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”?