The Basics of WordPress and jQuery Plugin

Exclusive offer: get 50% off this eBook here
WordPress 3.0 jQuery

WordPress 3.0 jQuery — Save 50%

Enhance your WordPress website with the captivating effects of jQuery.

£16.99    £8.50
by Tessa Blakeley Silver | September 2010 | Open Source WordPress

In the previous article, Understanding jQuery and WordPress Together, we took a look at the WordPress theme and how to edit it.

In this article by Tessa Blakeley Silver, author of Wordpress 3.0 jQuery, we will understand the following:

  • Overview of WordPress and jQuery Plugin
  • The basics of WordPress Plugin
  • The basics of jQuery Plugin

 

WordPress 3.0 jQuery

WordPress 3.0 jQuery

Enhance your WordPress website with the captivating effects of jQuery.

  • Enhance the usability and increase visual interest in your WordPress 3.0 site with easy-to-implement jQuery techniques
  • Create advanced animations, use the UI plugin to your advantage within WordPress, and create custom jQuery plugins for your site
  • Turn your jQuery plugins into WordPress plugins and share with the world
  • Implement all of the above jQuery enhancements without ever having to make a WordPress content editor switch over into HTML view

 

Read more about this book

(For more resources on WordPress and jQuery, see here.)

WordPress plugins overview

So themes change the look of WordPress without affecting its functionality. But what if you want to change or add functionality? WordPress plugins allow easy modification, customization, and enhancement to a WordPress site. Instead of having to dig in to the main files and change the core programming of WordPress, you can add functionality by installing and activating WordPress plugins.

The WordPress development team took great care to make it easy to create plugins using access points and methods provided by the WordPress' Plugin API (Application Program Interface). The best place to search for plugins is: http://wordpress.org/extend/plugins/. The following is a screenshot of the WordPress plugin directory's main page:

(Move the mouse over the image to enlarge.)

Once you have a plugin, it's a simple matter of decompressing the file (usually just unzipping it) and reading the included readme.txt file for installation and activation instructions. For most WordPress plugins, this is simply a matter of uploading the file or directory to your WordPress installation's wp-content/plugins directory and then navigating to the Administration | Plugins | Installed panel to activate it. The next screenshot shows the Plugins admin panel with the activation screen for the default Askimet, Hello Dolly, and new WordPress Importer plugins:

So how does a WordPress plugin differ from a jQuery plugin? In theory and intent, not that much, but in practice, there are quite a few differences. Let's take a look at jQuery plugins.

jQuery plugins overview

jQuery has the ability to allow you to take the scripts that you've created and encapsulate them into the jQuery function object. This allows your jQuery code to do a couple of key things. First, it becomes more easily ported over to different situations and uses. Second, your plugin works as a function that can be integrated into larger scripts as part of the jQuery statement chain.

The best place to browse for jQuery plugins is the jQuery plugins page (http://plugins.jquery.com/), as seen in the next screenshot:

In addition to having jQuery already bundled, WordPress has quite a few jQuery plugins already bundled with it as well. WordPress comes bundled with Color, Thickbox as well as Form and most of the jQuery UI plugins. Each of these plugins can be enabled with the wp_enqueue_script either in the theme's header.php file or function.php file, in WordPress. In this article, we'll shortly learn how to enable a jQuery plugin directly in a WordPress plugin.

Of course, you can also download jQuery plugins and include them manually into your WordPress theme or plugins. You'd do this for plugins that aren't bundled with WordPress, or if you need to amend the plugins in anyway.

Yes, you've noticed there's no easy jQuery plugin activation panel in WordPress. This is where understanding your chosen theme and WordPress plugins will come in handy! You'll soon find you have quite a few options to choose from when leveraging jQuery. Now that we have an overview of what WordPress themes, plugins, and jQuery plugins are, let's learn how to take better advantage of them.

The basics of a WordPress plugin

The goal here is to show you the structure of a simple WordPress plugin and the basics of how to construct one. Understanding this, you can begin to write your own basic plugins and feel more confident looking through other people's plugins when assessing what kind of features they provide to your WordPress site and if you need to tweak anything for your jQuery enhancements. Even as simply and basically as we're going to work, you'll see how truly powerful WordPress plugins can be.

Want to become a WordPress plugin rockstar?
You can start off with, yet again, WordPress 2.7 Complete by April Hodge Silver and Hasin Hayder. There's a chapter on plugins that walks you through creating very useful simple plugins, as well as a more complex plugin that writes to the WordPress database. Beyond that, you'll want to check out WordPress Plugin Development: Beginner's Guide by Vladimir Prelovac. Don't let the title fool you, Vladimir will have you generating feature rich and dynamic WordPress plugins using WordPress' coding standards all explained with clear, step-by-step code.

Working with plugins does require some experience with PHP. I'll keep this explanation fairly straightforward for non-PHP developers, and those of you with PHP experience should be able to see how to expand on this example to your advantage in WordPress.

Just as with themes, WordPress plugins require a little structure to get started with them. There's no defined hierarchy for plugin files, but you do need, at the very least, a PHP file with a special comment up top so that WordPress can display it within the Plugin Management page. While there are some single-file plugins out there, such as the Hello Dolly plugin, which comes with your WordPress installation, you never know when you first start developing, the ways in which a plugin may grow. To be safe, I like to organize my plugins into a uniquely named folder. Again, like with themes, WordPress relies on the plugin directory's namespace, so uniqueness is of key importance!

In the wp-content/plugins directory you can place a unique folder and inside that, create a .php file, and at the beginning of the file, inside the <?php ?> tags, include the following header information. Only the bold information is absolutely required. The rest of the information is optional and populates the Manage Plugins page in the Administration panel.

<?php
/*
Plugin Name: your WordPress Plugin Name goes here
Plugin URI: http://yoururl.com/plugin-info
Description: Explanation of what it does
Author: Your Name
Version: 1.0
Author URI: http://yoururl.com
*/
//plugin code will go here
?>

Make sure that you don't have any spaces before your <?php tag or after your ?> tag. If you do, WordPress will display some errors because the system will get some errors about page headers already being sent.

Once you have your .php file set up in its own directory, inside your plugin directory, you can add a basic PHP function. You can then decide how you want to evoke that function, using an action hook or a filter hook. For example:

<?php
/*
Plugin Name: your WordPress Plugin Name goes here
Plugin URI: http://yoururl.com/plugin-info
Description: Explanation of what it does
Author: Your Name
Version: 1.0
Author URI: http://yoururl.com
*/
function myPluginFunction(){
//function code will go here
}
add_filter('the_title', 'myPluginFunction');
//or you could:
/*add_action('wp_head', 'myPluginFunction');*/
?>

If you didn't have wp_head or wp_footer in your theme, many plugins can't function, and you limit yourself to the plugins you can write. In my plugins, I mostly use wp_header and the init action hooks.

Luckily, most filter hooks will work in your plugins as WordPress will run through them in The Loop. For the most part, you'll get the most work done in your plugin using the_title and the_content filter hooks. Each of these filter's hooks will execute your function when WordPress loops through those template tags in the loop.

Want to know what filter and action hooks are available?
The list is exhaustive. In fact, it's so immense that the WordPress codex doesn't seem to have them all documented! For the most complete listing available of all action and filter hooks, including newer hooks available in version 2.9.x, you'll want to check out Adam Brown's WordPress Hooks Database: http://adambrown.info/p/wp_hooks.
Overwhelmed by the database? Of course, checking out Vladimir's WordPress Plugin Development: Beginner's Guide will get you started with an arsenal of action and filter hooks as well.

You now understand the basics of a WordPress plugin! Let's do something with it.

Project: Writing a WordPress plugin to display author bios

As we've discussed, plugins can help expand WordPress and give it new functionality. However, we've seen that adding jQuery scripts directly to the theme and editing its template pages here and there will do the trick in most cases. But let's imagine a more complicated scenario using our modified default theme and the hypothetical client.

While we tweaked the default theme, I figured that this client might want to have her site's focus be more journalism oriented, and thus, she'd want some attention drawn to the author of each post upfront. I was right, she does. However, there's a catch. She doesn't just want their WordPress nickname displayed; she'd prefer their full first and last name be displayed as well, as it's more professional. She'd also like their quick biography displayed with a link to their own URL and yet, not have that information "get in the way" of the article itself, or lost down at the bottom of the post. And here's the really fun part; she wants this change affected not just on this site, but across her network of genre-specific news sites, over 20 of them at last count (dang, I forgot she had so many sites! Good thing she's hypothetical).

For this specific WordPress site, it's easy enough to go in and comment out the custom function we dealt with earlier: add in the_author tag and display it twice, passing each tag some parameters to display the first and last name. I can also add a tag to display the author's biography snippet from the user panel and URL (if they've filled out that information). Also, it's certainly easy enough to add a little jQuery script to make that bio div show up on a rollover of the author's name. However, having to take all that work and then re-copy it into 20 different sites, many of which are not using the default theme, and most of which have not had jQuery included into their theme, does sound like an unnecessary amount of work (to boot, the client has mentioned that she's deciding on some new themes for some of the sites, but she doesn't know which sites will get what new themes yet).

It is an unnecessary amount of work. Instead of amending this theme and then poking through, pasting, testing, and tweaking in 20 other themes, we'll spend that time creating a WordPress plugin. It will then be easy to deploy it across all the client's sites, and it shouldn't matter what theme each site is using. Let's get started!

WordPress 3.0 jQuery Enhance your WordPress website with the captivating effects of jQuery.
Published: September 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

Read more about this book

(For more resources on WordPress and jQuery, see here.)

Coding the plugin

First up, looking through the client's network of sites, not many display the author's nickname or name. Only a handful do and of those, the name is listed unobtrusively. It will be much easier to have a plugin display the author's name and then comment out or remove the_author tag from a few themes.

Here's a quick detail to note: template tags don't do so well in plugins. This is because the template tag, which is a function, is set to display text, which, within another function, we don't really want. What we want to do is get the information and pass it to our hook, which will display it when the plugin function runs. Most template tags have comparable WordPress functions, which will only get the information and not write or display it immediately. For writing plugins, instead of looking through the WordPress Codex's Template Tag function list, I like to look through the Function Reference. Just about anything that starts with get_ will work great in a plugin. For more details, have a look at http://codex.wordpress.org/Function_Reference.

The Codex Function Reference has get_the_author() which would suit some of my needs for this project, but I prefer to use a newer function that came about in WordPress version 2.8, called get_the_author_meta(). Unlike get_the_author, you can pass this function over 25 parameters to find out just about anything you care to on a WordPress user.

Given next is my plugin's base addAuthor function, followed by my add_filter hook which will run my function on every post's content. You can read the comments in bold for more detail:

...
//add author function
function addAuthor($text) {
/*the $text var picks up content from hook filter*/
//check if author has a url, a first name and last name.
//if not, no "Find out more" link will be displayed
//and just the required nickname will be used.
if (get_the_author_meta('user_url')){
$bioUrl = "<a href='".get_the_author_meta('user_url')."'>
Find Out More</a>";
}
if (get_the_author_meta('first_name')
&& get_the_author_meta('last_name')){
$bioName = get_the_author_meta('first_name').
" ".get_the_author_meta('last_name');
}else{
$bioName = get_the_author_meta('nickname');
}
//check if author has a description, if not
//then, no author bio is displayed.
if (get_the_author_meta('description')){
$bio = "<div class='authorName'>by <strong>".$bioName."</strong>
<div class='authorBio'>"
.get_the_author_meta('description')." ".$bioUrl."
</div>
</div>";
}else{
$bio = "<div class='authorName'>
by <strong>".$bioName."</strong>
</div>";
}
//returns the post content
//and prepends the bio to the top of the content
return $bio.$text;
}//addAuthor

//calls the post content and runs the function on it.
add_filter('the_content', 'addAuthor');
...

You'll note that in the previous code snippet I took some extra care to check if the WordPress user has a URL filled out in their profile, and if they've added in their first and last name as well as a bio description. If they don't, my plugin will merely display the user's nickname (the nickname is a required field) which is usually the same as the user's login name.

If any author doesn't have their first and last name, or a biography filled out, I'll leave it up to our client to force them to update their profile. In the meantime, the plugin won't display anything blank, empty, or broken, so no harm done.

Right now I'm just focused on getting the author's name and bio into WordPress, and now that the name and bio should be getting generated, I just want to make sure that the biography is styled nicely so that it stands apart from the post content but doesn't draw too much attention to itself.

To accomplish this, I'll add a stylesheet called authover.css to my plugin directory and add the following style to it:

.authorBio {
border-top: 2px solid #666;
border-bottom: 2px solid #999;
background-color: #ccc;
padding: 10px;
font-size: 10px;
}

Now, the reason why I placed the CSS inside its own stylesheet instead of scripted as a string into the plugin as another function was mostly to illustrate the best practice of using the wp_register_style and wp_enqueue_style functions from the Script API. Just as using the wp_enqueue_scripts function helps us avoid conflict with other JavaScript and jQuery libraries, these functions register the new stylesheet and load it up, ensuring that there won't be any conflicts with other same-named stylesheets.

For a stylesheet I'm pretty sure it will be unique to my plugin, and even more, just for a single rule, this may be overkill, but you should be aware of this method, especially since you'll probably run into it looking through more robust popular plugins. Also, this makes the plugin more easily extendable in the future. You won't need to futz through your PHP string to edit or amend the CSS. In fact, if you were to write a plugin that had a lengthy enough stylesheet, you could hand the stylesheet over to a CSS designer while you focused on the PHP functionality. Not to mention, this makes your plugin useful to other users. A WordPress user with no PHP experience could download and install this plugin and easily edit its CSS stylesheet so that it looks good with their site's design.

Here's my addCSS function. Also, afterward instead of activating the stylesheet off a filter hook, I want the stylesheet to register and load as soon as WordPress loads up, even before the wp_head hook! Hence, you'll see that I've used the init action hook.

You'll note in addition to my comments in bold, the use of the WP_PLUGIN_URL variable. This is similar to the TEMPLATEPATH variable I showed you in the theme section to create a custom include, except of course, this works inside plugins to help WordPress dynamically find your plugin files without you hard coding them in.

Please read the bold comments in the next code block to understand what each code statement does:

...
// Some CSS to position for the paragraph
function authorCSS() {
//These variables set the url and directory paths:
$authorStyleUrl =
WP_PLUGIN_URL . '/add_author_bio-tbs/authover.css';
$authorStyleFile =
WP_PLUGIN_DIR . '/add_author_bio-tbs/authover.css';
//if statement checks that file does exist
if ( file_exists($authorStyleFile) ) {
//registers and evokes the stylesheet
wp_register_style('authorStyleSheet', $authorStyleUrl);
wp_enqueue_style( 'authorStyleSheet');
}
}

//evoke the authorCSS function on WordPress initialization
add_action('init', 'authorCSS');

OK! That should do it. We now need to activate our plugin and check it out in WordPress.

Activating our plugin in WordPress

Our plugin is already in the WordPress wp-content/plugins directory. That means all we have to do is navigate over to our Manage Plugins page and activate it.

The plugin called jQuery Add Author Biography in the Plugin Name: space in the code's comment header appears in the plugins table as shown in the next screenshot:

Once the plugin is activated, we can navigate to the site to see it in action:

The Basics of WordPress and jQuery Plugin

It's working! The theme, which does not have the_author_meta tags in it, is now displaying the author's full name and bio description underneath it. The biography description is styled using the CSS rule in our plugin's class.

You've now edited a theme by hand and further extended the site by creating a WordPress plugin from scratch. Great job! But what's that you say? You were expecting to do a little more jQuery? You're right. Let's enhance this site a little further by creating a jQuery plugin.

The basics of a jQuery plugin

We'll discover that compared to WordPress themes and plugins, jQuery plugins are actually not that complex.

To set up a jQuery plugin, you need to follow jQuery's plugin construct. The basic construct consists of setting up a jQuery function for your plugin as follows. Note the bold .fn added to the jQuery object. This is what makes your function a jQuery function.

jQuery.fn.yourFunctionName = function() {
//code
};

Within that, it's best practice to then add a return this.each(function(){...}); so that your function will run through each item in the jQuery selector.

jQuery.fn.yourFunctionName = function() {
return this.each(function(){
//code
});
};

Unlike WordPress, which requires specifically formatted comments in theme CSS stylesheets and in plugin headers, jQuery does not require a commented-out header, but it's nice to add one up top.

/*
You can name the plugin
Give some information about it
Share some details about yourself
Maybe offer contact info for support questions
*/
jQuery.fn.yourFunctionName = function() {
return this.each(function(){
//code
});
};

Note that each function and method you wrap your plugin in and use inside your plugin must end in a ";" semicolon. Your code may otherwise break, and if you ever compress it, it will definitely break.

That's it, all that's required of a jQuery plugin. Now, let's dive in to enhancing the output of our WordPress plugin with a jQuery plugin.

Project: jQuery fade in a child div plugin

Taking the required jQuery function discussed previously, I'm going to write up a basic function, which can be passed not only to the main jQuery wrapper selection, but an additional selector parameter so that it's easy to target the child div of a selection, or the specific parameter of the jQuery selection that's passed the parameter.

Again, note the bold comments in my authorHover function to follow along:

...
//sets up the new plugin function: authorHover
jQuery.fn.authorHover = function(applyTo) {
//makes sure each item in the wrapper is run
return this.each(function(){
//if/else to determine if parameter has been passed
//no param, just looks for the child div

if(applyTo){
obj = applyTo
}else{
obj = "div";
}

//hides the child div or passed selector
jQuery(this).find(obj).hide();

//sets the main wrapper selection with a hover
jQuery(this).css("cursor", "pointer").hover(function(){

//restyles the child div or passed selector
// and fades it in
jQuery(this).find(obj).css("position","absolute")
.css("margin-top","-10px").css("margin-left","-10px")
.css("width","400px")
.css("border", "1px solid #666").fadeIn("slow");
},
function(){
//fades out the child selector
jQuery(this).find(obj).fadeOut("slow");
});
});
};

That's all it takes. Now that we've created a jQuery plugin script, let's quickly test it out in our theme first. All we have to do is embed our new jQuery plugin named jquery.authover.js to our theme, under the wp_enque_script call, below the wp_head hook and evoke it with a simple script:

...
<script type="text/javascript">
jQuery(function(){
jQuery(".authorName").authorHover();
});
</script>
...

We can take a look at the results in our site. I've grabbed two screenshots so that you can see the fade-in effect. In the following screenshot you can see the new div start to fade in:

The Basics of WordPress and jQuery Plugin

In this next screenshot you can see the completed fade animation:

The Basics of WordPress and jQuery Plugin

Extra credit: Adding your new jQuery plugin to your WordPress plugin

Now you're free to go and install your WordPress plugin and include jQuery plugin on as many sites as needed! However, in case you're wondering, yes, we can refine the installation process a bit more and just incorporate this jQuery plugin inside our WordPress plugin.

The first step is to simply drop our jquery.authover.js script inside our plugin directory and then use the wp_enqueue_script to evoke it. You'll want to pay particular attention to this use of the wp_enqueue_script function, as it will also include jQuery 1.4.2 IF its NOT already registered in the theme or plugin! This means that client's sites, which don't already have jQuery included, don't need to worry! Just installing this plugin will automatically include it!

...

function addjQuery() {
wp_enqueue_script('authover',
WP_PLUGIN_URL . '/add_author_bio-tbs/jquery.authover.js',
array('jquery'), '1.4.2' );
}

...

We'll then add a function to our WordPress plugin which writes in the jQuery script that uses the authorHover function of the plugin. Normally, it would be better, and it is recommended to load up all scripts through the wp_enque_script function, but for very small scripts that are so customized, you're sure will not ever conflict, and you know jQuery is already loading in properly (as we are with the plugin), if you want, you can just hardcode script tags like so:

...
function addAuthorHover(){
echo '<script type="text/javascript">
jQuery(function(){
jQuery(".authorName").authorHover();
});
</script>';
}
...

Lastly, we add the action filters which will evoke those functions:

...

add_action('init', 'addjQuery');

add_action('wp_head', 'addAuthorHover');
?>

Now, if you remove your jQuery plugin from your theme and make sure that your plugin is activated, you should see the exact same results as before! In the next screenshot, you'll notice that I've added a URL to my profile, and now the Find Out More feature set to degrade nicely if no URL was present, just automatically works. Wonderful.

The Basics of WordPress and jQuery Plugin

Putting it all together: Edit the theme or create a custom plugin?

We've learned in this article how easy it is to edit a theme, create a WordPress plugin, and a jQuery plugin. For the majority of your WordPress development work, adding jQuery enhancements right to the theme will do the trick. If you feel your jQuery scripts are a bit cumbersome and you're allowed to edit the theme (assuming of course, you don't break the layout or dramatically alter the look) you'll probably find that being able to wrap WordPress content in custom HTML tags with special class or id attributes is a huge help and time saver.

This article's project example's "hypothetical client request" also showed that if there's any chance that your work can or will be reused or deployed across multiple individual WordPress installations, you should consider encapsulating the work in either a jQuery plugin, a WordPress plugin, or as we discovered, both.

In addition to considering if your work will need to be reused or deployed, you may also want to consider the lifespan of the jQuery enhancement and that of the WordPress theme. It's easy to think that the jQuery enhancement is really more a part of the theme as it visually affects it, but is it really? I've found that more often than not, a large part of my WordPress and jQuery development seems to center around encapsulating jQuery development into a WordPress plugin, or making WordPress plugins more effective with jQuery.

As there are only two ways to include jQuery into a WordPress site, through the theme, or a plugin, if you're at all comfortable with editing and creating plugins, you'll probably start to find that its the better way to go (sure, there are always exceptions). Enhancing WordPress plugins with jQuery and even encapsulating jQuery plugins in WordPress plugins will allow you to easily scale your theme design and any jQuery functionality/enhancements independently of each other.

This approach comes in very handy if you do like to redesign or update your theme a lot, or perhaps you have a client who's a little "theme swap happy". If you want to keep the cool jQuery enhanced forms, image and gallery lightboxing, and various other functionality, or even just "neat eye candy" that you've created for a site, without having to manually update a new theme constantly with all of that over and over again, creating a plugin is the way to go, be it for jQuery, WordPress, or both.

Summary

You should now understand the following:

  • What WordPress plugins and jQuery plugins are.
  • How to create your own basic WordPress and jQuery plugins.
  • Best practices for knowing when to edit and customize a theme, or make a WordPress plugin, a jQuery plugin, or all three!

Further resources on this subject:


WordPress 3.0 jQuery Enhance your WordPress website with the captivating effects of jQuery.
Published: September 2010
eBook Price: £16.99
Book Price: £27.99
See more
Select your format and quantity:

About the Author :


Tessa Blakeley Silver

Tessa Blakeley Silver's background is in print design and traditional illustration. She evolved over the years into web and multi-media development, where she focuses on usability and interface design. Prior to starting her consulting and development company hyper3media (pronounced hyper-cube media) http://hyper3media.com, Tessa was the VP of Interactive Technologies at eHigherEducation, an online learning and technology company developing compelling multimedia simulations, interactions, and games that met online educational requirements like 508, AICC, and SCORM. She has also worked as a consultant and freelancer for J. Walter Thompson and The Diamond Trading Company (formerly known as DeBeers) and was a Design Specialist and Senior Associate for PricewaterhouseCoopers' East Region Marketing department. Tessa authors several design and web technology blogs. Joomla! Template Design is her first book.

Books From Packt


WordPress 3 Site Blueprints
WordPress 3 Site Blueprints

WordPress 2.8 Themes Cookbook
WordPress 2.8 Themes Cookbook

WordPress 2.9 E-Commerce
WordPress 2.9 E-Commerce

WordPress 2.8 Theme Design
WordPress 2.8 Theme Design

jQuery 1.4 Reference Guide
jQuery 1.4 Reference Guide

Learning jQuery 1.3
Learning jQuery 1.3

Nginx HTTP Server
Nginx HTTP Server

Drupal 7
Drupal 7


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software