Today’s WordPress tip of the day is “Using Jquery with WordPress”
add_action( ‘get_header’, ‘script_function’ );
alert( ‘hello’ );
While this method will do the trick it can become quite cumbersome. You have to be careful of which order you call this script in case it has dependencies on other scripts like jquery.
It is also not very organized to mix js with php.
Here is a better way:
One of the many great things about WordPress, is it has the latest version of Jquery built right in. There is also a hook built in to add scripts to your site.
Start with a hook called ‘wp_enqueue_scripts” and call the ‘wp_enqueue_script‘ function inside it like so.
add_action( ‘wp_enqueue_scripts’, ‘add_my_script’ );
apply_filters( ‘my_plugin_script’, ‘my_script’ ), //Allows developers to overright the name of the script
get_bloginfo( ‘stylesheet_directory’ ) . ‘/js/’ . ‘custom_script.js’, //The location of your script file
array(‘jquery’ ), //The scripts this depends on?
‘1.0.0’ //The Version of your script
Let’s take a look at the arguments above.
- The first one“apply_filters( ‘my_plugin_script’, ‘my_script’ )” is what names your script. You want this to be unique. Using apply_filters is optional but it lets other developers rename it in case of other scripts with the same name. If there are two same named scripts, WordPress with Go with the latest one only.
- The Second one “get_bloginfo( ‘stylesheet_directory’ ) . ‘/js/’ . ‘custom_script.js'” is where your file is located. In this example I used a handy little function which gives the directory of your active theme wherever it happens to be.
- The Third one “array(‘jquery’ )” is an array the names of any scripts that yours depends on. To use the built in Jquery use this example.
- The Fourth one “1.0.0” is the version of your script. This is caching purposes. If you change your script it’s a good idea to change the version as well.
//You call your jquery like normal inside this function//$(‘input’).val( ‘ ‘ );