Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load jQuery into WordPress properly

I have a WordPress site that I would like to use a jQuery plugin called DataTables. I've been having troubling figuring out the right way to load the jQuery script and the DataTables script into WordPress.

I know I'm supposed to use something with: wp_enqueue_script("jquery") - but I do not know where to put it or how to load the other jQuery plugin i need.

The last bit I tried was putting this in the header.php file for my WordPress site:

<?php wp_enqueue_script("jquery"); ?>

<?php wp_head(); ?>

Any help would be greatly appreciated!

like image 250
grad_student Avatar asked Mar 06 '14 20:03

grad_student


People also ask

Is jQuery loaded in WordPress?

To run the jQuery scripts on the WordPress website, you need to add the appropriate libraries. But fortunately, the WordPress structure already includes all the necessary libraries. To make them work, you just need to connect them to your theme.

Is jQuery necessary for WordPress?

While it has been widely known that you might not need jQuery for most of your interactive theme features, jQuery is still a common JavaScript dependency found in WordPress themes – for example, 7 out of the 11 default themes since Twenty Ten are using jQuery in the frontend.

Should jQuery be in header or footer?

It's always a good practice to add jQuery code in footer i.e. just before the closing </body> tag. If you have not done that, then use the defer attribute. The defer attribute is used to specify that the script execution occurs when the page loads.


1 Answers

jQuery is included in WordPress core and when you include your javascript, you can declare that your script is dependent on jquery being loaded as the third parameter of wp_enqueue_script: http://codex.wordpress.org/Function_Reference/wp_enqueue_script.

The proper way to use wp_enqueue_script is to include it in a callback that is attached to a specific action hook. That sounded incredibly complicated to me when I started with WordPress, but it's actually a really good system because it allows you to specify when your code should run during the initialization of WordPress.

So, in your functions.php or a plugin, you add your hook.

add_action( 'wp_enqueue_scripts', 'my_js_include_function' );

Then, in that function, you running the actual inclusion, and declare that your script is dependent on jquery.

function my_js_include_function() {
    wp_enqueue_script( 'my_script.js', '/path/to/myscript.js', array('jquery') );
}

The first parameter of wp_ennqueue_script() is an arbitrary name you are assigning to your script. If you were to then declare another script was dependent on the original one, that's how you would refer to it in the third parameter.

like image 157
Andrew Bartel Avatar answered Sep 24 '22 06:09

Andrew Bartel