Enable jQuery with the dollar sign ($) in Wordpress
Posted in Uncategorized on April 20th, 2009 by admin – Be the first to commentLike many avid jQuery users, I was often frustrated when trying to develop my own theme or plugin for Wordpress and found that I could not use the $ shortcut for jQuery. While this is not much of a problem if I was writing my own program, I was trying to incorporate the plugins that other users had created. Unfortunately, there is no nice answer to this problem.
Wordpress by default loads prototype on the main blog, without jQuery. The admin pages of Wordpress use both prototype and jQuery.
Load jQuery on the main blog
To load jQuery on the main blog, you need to make use of Wordpress’s wp_enqueue_script function. Here is a sample chunk of php code to use to include jQuery. Simply put this at the beginning of your header.php file, before the Doctype declaration:
<?php
function loadScripts(){
wp_enqueue_script(‘jquery’);
}
add_action(‘wp_print_scripts’,loadScripts);
?>
This will load the jquery library when the other scripts Wordpress automatically inserts into your pages are added.
Use the $ sign in your jQuery plugin
To use the $ sign in your jQuery plugin, simply include the following line at the beginning:
var $ = jQuery;
This will override the global prototype shortcut which uses the $ sign for your plugin.
How do I incorporate other jQuery plugins?
To add a plugin for jQuery, you need to first load it with the wp_enqueue_script function, and then resolve the issue of the $ sign in one of three ways:
- Do a find-and-replace in the plugin javascript to replace all occurrences of ‘$‘ with ‘jQuery.’
- Include the line of code from the above step at the beginning of the plugin javascript.
- Load a javascript file before the plugin file that contains the line of code from the above step.
For example, to include the dropshadow and rounded corners plugins:
<?php
function loadScripts(){
wp_enqueue_script(‘jquery’);
//You can use an absolute path, where ‘/’ is the root of your Wordpress installation.
wp_enqueue_script(‘master’,‘/wp-content/themes/Katz%20Dental/scripts/js/master.js’);
wp_enqueue_script(‘jquery.dropshadow’,‘/../scripts/js/jquery.dropshadow.js’);
wp_enqueue_script(‘jquery.corners’,‘/../scripts/js/jquery-corners-0.3/jquery.corners.js’);
}
add_action(‘wp_print_scripts’,loadScripts);
?>
This will load your master.js file, which contains the line of code that allows you to reassign the $ sign shortcut.
Voila! We now have jQuery up and running on Wordpress!