WordPress plugin development - how to use jQuery / javascript?

Just started developing a plugin for WordPress, I wanted to use jQuery in the Admin plugin interface.

How to enable and invoke jQuery?

For example, in a regular HTML page, I would just include the jQuery library, then call it a script:

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

How to do this in a WordPress plugin PHP file?

+6
source share
2 answers

First, you always need to use the no-conflict wrapper in Wordpress, so your code will look like this:

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

Secondly, it is good practice to place your javascript in external files, and in the Wordpress plugin you would include the following elements:

 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 jQuery as a dependency, so Wordpress will automatically load jQuery if it is not already loaded, so that it loads only once and loads before your script plugins.

And if you only need a script on the admin pages, you can load it conditionally using the 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 } 
+13
source

Using your own version of jQuery is not recommended.

WordPress includes its own version of jquery and many other similar JS files that have been thoroughly tested using WP and many of the most common plugins. To ensure the best compatibility and experience for our users, we ask you not to pack your own (especially the older version) and use wp_enqueue_script () instead to pull out the version of WordPress.

Therefore, you should use this instead:

 wp_enqueue_script('jquery') 
+3
source

Source: https://habr.com/ru/post/946124/


All Articles