How to Make a Custom jQuery WordPress Plugin

We love jQuery. A lot. And we use it a lot too. In fact, on pretty much every site we build, we utilize a common set of basic jQuery snippets that do some handy things (opening external links in a new window, adding helpful classes to list elements, labeling links based on there “href” attributes, etc). Sounds like the job for a simple plugin, right? No need to copy and paste all your snippets on each new project – you can create your own custom jQuery plugin in 4 easy steps:

1. Set Up Your Plugin

First thing you’ll want to do is create a new directory for your plugin. Name it something intuitive, like my-custom-jquery (typically all lowercase with hyphens).

In this new directory, create 2 new files:

  1. my-custom-jquery.php
    The file name should essentially match your plugin name.
  2. my-custom-jquery.js
    Similar naming scheme. We’ve chosen to name our file mightyminnow-custom-jquery.js in the code below.

Now you’re ready for the actual coding.

2. PHP (my-custom-jquery.php)

This is the guts of your plugin – your main PHP file.

This code does a few things:

  1. The first commented bit is a standard WordPress plugin information header. It contains important info about the plugin, such as author, URI’s, and a brief description.
  2. Further down, we have a basic function that does two things. First, it enqueues jQuery (notice the function wp_enqueue_script which is the safe and proper way to include jQuery in WordPress). Second, we enqueue our custom jQuery.
  3. Lastly, we add an action to run the whole shebang. We use the wp_enqueue_scripts hook, which is a good place to include all scripts.

3. jQuery (my-custom-jquery.js)

Now we just have to add our actual jQuery to the .js file we’ve made. Here is the code we’re using – feel free to add your own snippets as well.

As you can see, this jQuery does a number of things including:

  • Opens external links in a new window
  • Adds special classes to image, email, and pdf links (we often use these classes to add small background-image icons)
  • Add special classes to first, last, and parent list elements

This is where you can get creative and add whatever jQuery snippets you like to use on a regular basis. If you have any suggestions, definitely post them in the comments below!

4. Install Your Plugin

At this point, you’re ready to install your plugin. You’ve got two options. The first is just to upload your plugin folder directly to /wp-content/plugins. The second is to create a .zip of your plugin folder and use WordPress’ built-in plugin installer to upload it. Once it’s up and running, make sure to thoroughly test any jQuery snippets you’ve added, and definitely let us know what sorts of cool stuff you come up with.

Questions? Comments? Let us know below!