Minimal Wordpress JS plugin example

Also see: Minimal WordPress CSS plugin example Minimal WordPress Shortcode plugin example

This plugin adds a static Javascript .js file to Wordpress which is loaded in the client.

First, create a directory for your plugin in wp-content/plugins/, e.g. wp-content/plugins/my-js-plugin

Save the following code as functions.php in the plugin folder, e.g. wp-content/plugins/my-js-plugin/functions.php

<?php
/*
Plugin Name: My JS plugin
*/

function my_plugin_enqueue_js(){
    wp_enqueue_script('my-plugin-js', plugins_url('/script.js', __FILE__), false, '1.0.0', true /* in footer */);
}
add_action('wp_enqueue_scripts', "my_plugin_enqueue_js");

Next, save your desired JS file in script.js in the plugin folder, e.g. wp-content/plugins/my-js-plugin/script.js. Example script:

jQuery(document).ready(function() {
    console.info("Your JS plugin works!");
});

Now activate your plugin your Wordpress admin area.

Your Javascript will be loaded on each Wordpress page until you deactivate the plugin.

Note that if you are using a JS-optimizing plugin like Autoptimize, you might not actually see your JS file as separately loaded script file as it is compiled into the single Autoptimize JS. You javascript will still be loaded on the client!