Building my first theme from scratch in WordPress 3.4.1, I know WordPress already has the latest version of the JQuery via Google. I have read about issue’s if the script is not called properly, so want to try and keep everything as close to the recommended coding as possibly. I want to make sure the script is loaded which I believe is carried out by the below PHP script in the functions.php file (taken from the WordPress Codex).
<?php
function my_scripts_method() {
wp_enqueue_script( 'jquery' );
}
I want to basically have a custom menu using JQuery, so is it just a case of placing the script I want to activate in the header or PHP section?
Also if I wanted to enqueue another script that is not included in the WordPress already, do I simply add the below PHP to the above code in the functions.php file?
wp_register_script( 'jqueryexample', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jqueryexample.min.js');
I am ok with HTML and CSS but PHP and JAVA is relatively new to me, any help is greatly appreciated.
Thanks,
Ant
You’re on the right track, but missing one piece:
add_action allows you to run code at specific times during page loads / specific events. The above action tells WP to run your function when it is adding the scripts to the html head element. Your function in turn instructs WP to add the jQuery script.
The same goes for registering a new script, but with a different hook:
If you’re overriding a pre-registered script, you should also first deregister that script. I use something like the following code to replace the jquery script (note: read 2nd edit at the end):
As to where you should put that code. If the code is specific to the theme, you should put it in functions.php in your theme folder. If you’re going to re-use the code on multiple theme’s, it would be easier to maintain a plugin with all shared code.
Edit:
As Stephen Harris notes below, since WP 3.3 you can also use
wp_enqueue_scripts
afterwp_head
has triggered, for example in shortcodes or widgets. The js will then be loaded in the footer.Edit 2:
For jQuery and other google hosted libraries it is recommended that you use http://wordpress.org/extend/plugins/use-google-libraries/
Read the comments for a motivation by Otto.
You must use
wp_enqueue_script
to load the script for your theme, the functionwp_register_script
only register the script with a keyword.This will simply regiter new script with name
jqueryexample
and you can load that script whenever necessary usingwp_enqueue_script
function.Here is sample code to load already register script i.e. jQuery and a new own script i.e. jQuery Exmple
However you can use only the
wp_enqueue_scripts
function to load a remote JavaScript, Here is an example –