Plugins are used to enhance the functionality of WordPress. These plugins use JavaScript to add interactivity. External JavaScript files are loaded into the plugin using the wp_enqueue_scripts action hook in WordPress. But, how do I load an external JavaScript file into a custom WordPress plugin? The same action hook (wp_enqueue_scripts) is used in loading JavaScript in developing custom plugin.
In this tutorial, I’ll show how to increase the plugin’s interactivity by loading a JavaScript file with a WordPress plugin. To understand this tutorial you should have minimal experience developing custom WordPress plugins.
This task can be accomplished in several ways. Three well-known methods are:
- Using WordPress’s wp_enqueue_scripts action hook.
- Using wp_footer and wp_head hooks.
- Using third-party WordPress plugins.
In this tutorial post, I will discuss how to use the wp_enqueue_scripts hook by following the first method.
Loading JavaScript files using the wp_enqueue_scripts action hook
- In the root folder of the custom plugin, create another folder named assets and js in it. Create a file called plugin-name.js in this folder.
- Add the following line to the main file of the custom plugin. It uses a custom function via the wp_enqueue_scripts action hook.
add_action('wp_enqueue_scripts', 'custom_plugin_name_js'); function custom_plugin_name_js() { wp_enqueue_script( 'plugin-name-js', plugins_url( '/assets/js/plugin-name.js', FILE ), array('jquery'), 1.0, true); }
- Now write the necessary codes for the interactivity of the plugin in the plugin-name.js file. By convention, we can add the following file to make sure that this JavaScript file is loaded correctly.
alert('Custom Plugin Name loaded.');
In this tutorial we saw how to load a JavaScript file with a custom WordPress plugin using the wp_enqueue_script action hook. For more details on this enqueue hook visit WordPress’s official documentation page.
Leave Your Comment