After having used jQuery and WordPress together on a number of themes, I thought I’d share some tips that I have learned through my experience with WordPress.
The traditional way to include jQuery in an HTML page is with the script tag. However when working with WordPress, you should never do this. The reason is to avoid conflicts and other potential problems such as erros with other plugins. Here is how WordPress recommends to load jQuery using the following code:
Code
/** * Enqueue jQuery script */ function load_jQuery_script() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://code.jquery.com/jquery-latest.min.js', array(), '', false); wp_enqueue_script('jquery'); } } add_action( 'wp_enqueue_scripts', 'load_jQuery_script' );
What did we do?
if (!is_admin()): The is_admin() check is to prevent script queuing on your admin pages.
wp_deregister_script: De-registers the WordPress stock jquery script, so you can register your own copy.
wp_register_script: Registers the latest version of jQuery from the jQuery page. So you are sure to use the latest one and from the main source.
wp_enqueue_script: Give it the jquery name for the dependencies
You can replace load_jQuery_script with something more meaningful, but choose a unique name to avoid conflicts. For plugin development, add the code in your plugin file, otherwise, add this code to your theme’s functions.php file.
Load jQuery in the footer
/** * Enqueue jQuery script */ function load_jQuery_script() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://code.jquery.com/jquery-latest.min.js', array(), '', true); wp_enqueue_script('jquery'); } } add_action( 'wp_enqueue_scripts', 'load_jQuery_script' );
Just change in the wp_register_script(‘jquery’, ‘http://code.jquery.com/jquery-latest.min.js’, array(), ”, true); to ture.
Hope this quick tutorial helped you!