WordPress Plugin Development – How to use JQuery / JavaScript?

Solution:

Firstly, you always have to use a no-conflict wrapper in WordPress, so your code would look like :

jQuery(document).ready(function($){
    alert('Hello World!');
});

Secondly, it’s good practice to put your javascript in external files, and in a WordPress plugin you would include those like this :

wp_register_script( 'my_plugin_script', plugins_url('/my_plugin.js', __FILE__), array('jquery'));

wp_enqueue_script( 'my_plugin_script' );

This includes your script, and sets up jQuery as a dependency, so WordPress will automatically load jQuery if it’s not already loaded, making sure it’s only loaded once, and that it’s loaded before your plugins script.

And if you only need the script on the admin pages, you can load it conditionally using WordPress add_action handlers:

add_action( 'admin_menu', 'my_admin_plugin' );

function my_admin_plugin() {
    wp_register_script( 'my_plugin_script', plugins_url('/my_plugin.js', __FILE__), array('jquery'));
    wp_enqueue_script( 'my_plugin_script' );

    // do admin stuff here
}