JQuery in WordPress: 3 little things to avoid much head scratching
by Marie, May 24, 2012
Don’t get me wrong, I really like the WordPress doc. That’s one of the main reasons I’m sticking to WordPress. Yet… I found that learning to integrate and use jQuery in themes and plugins was a frustratingly hiccupy process. You know, when you spend ages scratching your head over message-less bugs just because there’s one tiny piece of information you did not have.
To save YOU those agonizingly slow and frustrating moments, here are a few things that I wish had been made clearer about jQuery in WordPress.
1. It’s already in!!
There is no need to add a copy of jQuery to your WordPress theme or plugin. It’s already there in the core package. You still need to call it though, just in case it wasn’t loaded yet.
Insert it using the wp_enqueue_script function; the handle for jQuery is simply… ‘jquery’.
2. Calling ‘$’ doesn’t work!
Nope you cannot write
$(document).ready(function(){});
as the ‘$’ is not recognized in Worpdress. You need to use ‘jQuery’ instead, like so
jQuery(document).ready(function(){});
If you absolutely want to use the ‘$’ call, you simply need to pass it as a variable from function to function.
jQuery(document).ready(function($){
anotherfunction($);
});
3. Passing variables to jQuery
At times, you will want to provide server-side variables to jQuery, a good example would be the path to your theme or plugin. But if you insert your script properly using the wp_enqueue_script function, how do you pass those variables to the jQuery environment?
Using the wp_localize_script function, which assigns an object containing the various variables you wish to transmit to your script.
See this page for details on its use: http://codex.wordpress.org/Function_Reference/wp_localize_script
More in future posts! Any questions, please ask in the comments
Category: Web pro stuff, Wordpress development | Tags: jquery, plugin development, theme development |

Be the first to comment!