jQuery in WordPress – The Good, The Bad, The Ugly

When I was an uber noob with jQuery and WordPress, I struggled to get my scripts to work properly. I looked at dozens of plugins and themes and found a varying number of ways others implemented jQuery. The following is my personal opinion from experience using jQuery and WordPress together.

The Good

jQuery(document).ready(function($){
    $('.something').each(function(){
        $(this).doSomething();
    });
});

I’ve found this to be the most elegant jQuery declaration that does not conflict with the WordPress UI or other plugins. Declare the jQuery function to start and feed the dollar sign parameter so the code inside looks neat and clean.

The Bad

$(function(){
    $('.something').each(function(){
        $(this).doSomething();
    });
});

Since several popular Javascript libraries use the dollar sign as their function name, it’s important to not assume the dollar sign is assigned to the jQuery library. By not declaring the jQuery function outright, you are almost certain to break the WordPress UI.

The Ugly

jQuery(function(){
    jQuery('.something').each(function(){
        jQuery(this).doSomething();
    });
});

Technically, this example is absolutely correct, however it’s not pretty. Who wants to write ‘jQuery’ a thousand times in their script? I prefer to declare the jQuery function once and substitute it with the dollar sign. It makes for a better visual and easier read.

The Acceptable

var $i = jQuery.noConflict();
$i(document).ready(function(){
    $i('.something').each(function(){
        $i(this).doSomething();
    });
});

If you’re really struggling to get jQuery working properly, you can use the jQuery.noConflict() function. I steer away from this method because I only use plugins that won’t cause massive conflicts of this nature. I only use this method when I’m backed in a corner with no other options.