Mat Lipe Dot Com

You Are Viewing

A Blog Post

Using Jquery with WordPress

Today’s WordPress tip of the day is “Using Jquery with WordPress”

When adding javascript or jquery to wordpress it is tempting to throw something into a header or footer hook that simply echos out a script tag like so

add_action( ‘get_header’, ‘script_function’ );

function script_function(){

echo ‘<script type=”text/javascript”>';

alert( ‘hello’ );

echo ‘</script>';

}

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:

Although, I am going to focus on Jquery this same method is proper practice for javascript by itself as well.

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’ );

 

function add_my_script(){
wp_enqueue_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.

  1. 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.
  2. 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.
  3. 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.
  4. 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.
Now your script will be included in the site’s head somewhere after Jquery is called. But, how do you use the Jquery we are used to?
If you are like me, you are used to using the “$” as your Jquery selector. Here is how you do this with WordPress:
jQuery(document).ready(function($){
//You call your jquery like normal inside this function
//$(‘input’).val( ‘ ‘ );
});
That’s it, you can now use your Jquery with wordpress!

 

 

 

 

 

Leave a Reply

The possibilities when designing a site with WordPress are immense indeed.

Get in Touch

Contact Me

Send a Message