Skip to content

Making jQuery Plugins into WordPress Plugins

We’ve never gotten fan mail before—and we still haven’t. But David’s article last week did draw a nice comment from a user thanking him for the knowledge drop.

It also contained a request, for “A complete example on how to fully implement jQuery plugins in a WordPress theme.” The commenter pointed out a number of free jQuery plugins that would be nice to implement in a WordPress environment.

So I figured, Why not dive into this? There are a lot of reasons to want to extend jQuery functionality into WordPress—which you’d do by embedding it in a WordPress plugin—and I thought exploring the process could be really helpful for readers.

I chose the easiest example from the commenter’s wishlist: a scroll-to-top jQuery script that zooms you back to the top of the page when you click an arbitrary element.

Today we’ll explore the process of turning that jQuery plugin into a WordPress plugin—with a brief detour into what “plugin” actually means, and why making different types of “plugins” talk to each other is not a simple or predictable process.

Before that, though, let’s do the big reveal: our scroll-to-top WordPress plugin in action!

The plugin: WPShout Scroll to Top

Now, let’s look at the process to convert the original jQuery functionality into a WordPress shortcode plugin.

Easier said than done

“Turning a jQuery plugin into a WordPress plugin” is not a simple or predictable process, despite both things containing the word “plugin.”

The first thing to make clear is that “turning a jQuery plugin into a WordPress plugin” is not an inherently simple or predictable process, despite both things containing the word “plugin.”

It’s a bit like “turning a birthday party into a political party”: it’s not totally nonsensical—I guess a bunch of partygoers could organize around a shared platform and try to gain representation—but it’s a much less seamless process than the shared use of “party” might indicate.

So we’ll first be exploring what “plugin” actually means, first in general, and then in a WordPress and a jQuery context. That ought to shed some light.

What a plugin is

“Plugin”—like “API” and a fair amount of other nerdspeak—is a very general term.

The current Wikipedia definition is satisfyingly vague: “In computing, a plug-in (or plugin, extension, or add-on/addon) is a software component that adds a specific feature to an existing software application.”

If I had to define it, I’d say a plugin is: “A non-standalone piece of software that adds helpful functionality to standalone software.” That adds basically nothing to the Wikipedia definition, but at least it’s a bit more plainspoken.

A plugin should hook simply and easily into its larger environment.

A corollary—and probably where “plugins” got the name—is the idea of “plug-and-play,” or “it just works.” This means that a plugin should work with minimal technical knowledge on the user’s part, and with minimal hooking-up of wires and tubes to get the desired functionality. In other words, a plugin should be a mass of mostly opaque code—code that the user never needs to interact with or understand—that hooks simply and easily into its larger environment.

WordPress plugins

Most WordPress plugins meet the above definitions. For example, Akismet is a very complex spam-filtering service with a very simple installation process and interface.

WordPress plugins also share some specific technical traits:

  • Installed through the “Plugins” interface in the WordPress admin
  • Usually located in the plugins directory in wp-content
  • Built around a core PHP file that declares the plugin in a WordPress-readable way

These attributes mean that WordPress plugins exist in a predefined technical relationship to the broader WordPress environment, whether their functionality is very simple (like today’s scroll-to-top demo) or very complex (like WooCommerce).

jQuery plugins

jQuery plugins meet the general definition of “plugin,” but here’s the thing: they’re mostly just blocks of jQuery code with no particular relationship to the broader environment they’re in, which could be basically anything.

To allow users to hook into their functionality, most jQuery plugins simply expose an API in the form of a single jQuery function with various function parameters as controls. That’s the case for our scroll to top demo, which we engage using the following function call (simplified from the example given in the plugin’s documentation):

$('body').scrollToTop({
	easing: 'easeInOutElastic',
	trigger: '.scrolltotop',
	speed: 1000,
	easing: 'linear'
});

So how to turn jQuery plugins into WordPress plugins?

To convert jQuery functionality into a WordPress plugin, we’ll need to do all the hook-up work ourselves.

The jQuery plugin in today’s demo is doing something useful that would be (at least a bit) tricky to code independently: scroll back to the top of the window, with all kinds of options for how quickly to scroll, where to scroll to, and which element triggers the scrolling.

But that—plus an API to use it, also written in jQuery—is all we get. To convert this functionality into a WordPress plugin, we’ll need to do all the hook-up work ourselves. This means we’ll need to:

    • Register the plugin in the WordPress way, with assets (like stylesheets and the jQuery plugin code itself) also registered in the WordPress way
    • Choose and implement a user interface, like a shortcode or a custom field, that will let users control when and how to use the plugin from within the WordPress admin
    • Hook WordPress up to the jQuery script API so that user actions (adding and removing shortcodes, checking and unchecking checkboxes) appropriately change the script’s behavior.

Now we’ll walk through that process as it applied in this example.

Anatomy of WPShout Scroll to Top

The plugin has four main files:

        1. The core PHP file that hooks into WordPress
        2. The main jQuery “plugin” file with the scrolling behavior
        3. A jQuery file that calls the jQuery plugin with certain parameters
        4. A minimal CSS stylesheet

There’s also a little PNG image file that I’m using as the clickable “to top” icon. The plugin looks as follows:

Scroll to Top plugin contents

Steps to create the plugin

Here’s what it took to turn “scroll to top” into a WordPress plugin. If you’ve never written a WordPress plugin before, you may enjoy David’s wonderfully lucid explanation of their basic features, as well as a bare-bones example of a plugin with a shortcode.

Registering the plugin

For WordPress to understand it, every plugin needs a bit of information at the top of its main PHP file. This lives in a commented-out section and looks, in our case, like this:

/* 
Plugin Name: WPShout Scroll to Top
Description: A demo of a jQuery plugin turned WP plugin. Scrolls to top through a shortcode.
Version: 1.0
Author: Press Up, Inc.
Author URI: http://www.pressupinc.com/
*/

Registering the plugin’s resources

The plugin relies on three main files—the two JavaScript/jQuery files and the CSS stylesheet—in addition to the core PHP plugin file.

The two jQuery files have a major dependency: jQuery itself. Since they can’t run without them, we’ll declare that dependency when we enqueue each script. The CSS can run as a standalone with no dependencies.

We want to make these all available, but only on pages that use the “scroll to top” behavior in the first place. In our case, “scroll to top” will be a shortcode, so we’ll search the post contents for that shortcode and only enqueue the scripts if we find what we’re looking for.

// Check to see if assets are needed and include them if so
// Code largely from https://pippinsplugins.com/load-scripts-if-post-has-short-code/
function pw_check_for_shortcode($posts) {

    if ( empty($posts) )
        return $posts;
 
    // False because we have to search through the posts first
    $found = false;

 
    // Search through each post
    foreach ($posts as $post) {

        // Check the post content for the shortcode
        if ( stripos($post->post_content, '[' . 'scrolltotop') ) {
            // We have found a post with the shortcode
            $found = true;
            // Stop the search
            break;
        }
    }
 
    if ($found){
        // Declare scripts with jQuery dependency, and the stylesheet with no dependencies
        wp_enqueue_script( 'scrolltotop-src', plugins_url( 'jquery-scrollToTop.js' , __FILE__ ), array('jquery') );
        wp_enqueue_script( 'scrolltotop', plugins_url( 'scrolltotop.js' , __FILE__ ), array('jquery') ); 
        wp_enqueue_style( 'scrolltotop', plugins_url( 'scrolltotop.css' , __FILE__ ) );
    }

    return $posts;
}
// Perform the check when the_posts() function is called
add_action('the_posts', 'pw_check_for_shortcode');

Registering the shortcode

add_shortcode('scrolltotop', 'wps_scrolltotop');
function wps_scrolltotop($atts) {

	extract(
		shortcode_atts( array(
 	      'text' => ''
    	), $atts, 'scrolltotop' )
    );

    if( $text == '' ) {
    	return '<' . 'img class="scrolltotop" src="' . plugins_url( 'cycle-hover.png' , __FILE__ ) . '" > ';
	}

	else {
		return '' . $text . '';
	}
}

Engaging the jQuery plugin through its API

Here’s where we wrote our API call for the jQuery function. We set a couple of parameters: how fast it goes to the top, and what kind of “swooshing” motion (or “easing”) it uses to get there. Most importantly, we set a “trigger” parameter that the plugin author provided so that the whole thing clicks into motion whenever the user clicks on anything with class scrolltotop. As you see in the shortcode declaration above, both implementations of the shortcode—either the arbitrary text or our little icon—wrap their contents in class “scrolltotop.”

(function($) {
	$(document).ready(function($) {
		$('body').scrollToTop({
			easing: 'easeInOutElastic',
			trigger: '.scrolltotop',
			speed: 1000,
			easing: 'linear'
		});
	});
}(jQuery));

Special note: jQuery anonymous functions

In the jQuery code above, note the anonymous function wrapper: (function($){ }(jQuery));. This is very important: it binds the “$” variable to jQuery within that code. Without it, the “$” variable might not work in a WordPress environment.

The jQuery plugin script itself does a similar kind of wrapping. If it didn’t, it would’ve been necessary to modify it to do so, or to replace “$” with “jQuery” throughout the code.

This is a very important note when you’re dealing with jQuery in WordPress. If it doesn’t make sense, it’s better explained here.

Styling the plugin

We did some minimal CSS styles to make the shortcode look pretty. For the most part, we relied on the same scrolltotop class that we used to trigger the jQuery plugin.

.scrolltotop {
	cursor: pointer;	
}

.entry-body img.scrolltotop {
	outline: 0;
	border: 2px #F15A23 dashed;
	border-radius: 50%;
	padding: 5px;
	display: block;
	margin: 1em auto;
}

Final notes

Once we know how to use a jQuery plugin’s API, we don’t need to know how the plugin itself works.

I thought it would be useful to call out the fact that we didn’t do anything with the original jQuery plugin itself. That’s the point: once we know how to use its API (in this case, the function that calls it and the function parameters that control it), we don’t need to know how it works. It’s a black box to us: we tell it to do its thing, and, mysteriously, it does—which was the whole point of finding a plugin in the first place.

And viola

And viola

The main exception to this rule is registering the “$” variable, described above. That’s a very simple syntactical fix and shouldn’t involve comprehending the plugin code on a deep level at all.At this point, we’ve covered the way the plugin interfaces between WordPress and its main jQuery functionality, and how it brings in other necessary resources along the way. And viola! We’re done.

In conclusion…

Well, that’s an example of extending simple jQuery functionality into a WordPress plugin. Most real-world examples would be more complex: you’d have to build a better-fleshed-out interface for them, for example. So if you’re set on bringing a specific piece of jQuery to your WordPress site, please bring your sturdiest welding torch, or budget for finding a good developer.

We hope you’ve learned that we love hearing from our readers, and may even spend a full day answering their questions in detail.

Hopefully you’ve learned a bit more about how to drop jQuery code into a WordPress plugin, and a bit more about why there’s no simple way to turn a “jQuery plugin” into a “WordPress plugin.”

We also hope you’ve also learned that we love hearing from our readers, and may even spend a full day answering their questions in detail—so please leave questions and comments below!

Finally, if something about this post is still sinking in and needs a reread, you can always [scrolltotop text=”scroll to top!”]

[scrolltotop]
Fred Meyer

3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
A Sparkling New Site, and a Look Ahead | WPShout.com
October 28, 2014 4:47 pm

[…] and explain? Tell us all about it, in the comments below or directly. Ask away! We’ve got a track record of turning questions into very detailed […]

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!

Most Searched Articles

Best JavaScript Libraries and Frameworks: Try These 14 in 2024

In this post, we look at the best JavaScript libraries and frameworks to try out this year. Why? Well, with JavaScript being available in every web browser, this makes it the most accessible programming language of ...

25 Best Free WordPress Themes (Responsive, Mobile-Ready, Beautiful)

If you're looking for only the best free WordPress themes in the market for this year, then you're in the right place. We have more than enough such themes for you right ...

12 Best WordPress Hosting Providers of 2024 Compared and Tested

Looking for the best WordPress hosting that you can actually afford? We did the testing for you. Here are 10+ best hosts on the market ...

Handpicked Articles

How to Make a WordPress Website: Ultimate Guide for All Users – Beginners, Intermediate, Advanced

Many people wonder how to make a WordPress website. They’ve heard about WordPress, its incredible popularity, excellent features and designs, and now they want to join the pack and build a WordPress website of their own. So, where does one get ...

How to Start an Ecommerce Business: Ultimate Guide for 2024

Is this going to be the year you learn how to start an eCommerce business from scratch? You’re certainly in the right place! This guide will give you a roadmap to getting from 0 to a fully functional eCommerce business. ...