Anatomy of a WordPress Plugin

Often times when you want something done correctly, it’s best to do it yourself. While certain aspects of WordPress may seem out of reach, we are lucky to have so many resources to pull from as we develop ourselves as coders. Since I periodically spend time in forums answering questions, i came across this question:

Can you recommend a good plugin to add Custom Jquery and Scripts?

Seemed to me that the easiest way to handle this was to create a plugin that specifically targeted the loading of scripts properly.

Since I usually just delete the Hello Dolly plugin anyway, I recommended following the structure of that plugin as a starting point. Instead of starting from scratch, overwriting the data would illuminate the elemental anatomy of a WordPress plugin.

For starters, the commented out code block at the top, in contrast to other comments in code, is the part that no self-respecting plugin can live without. WordPress will scan the plugin directory for this specific type of code block in order to programmatically find any and all available plugins.

<?php
/**
 * @package Hello_Dolly
 * @version 1.6
 */
/*
Plugin Name: Hello Dolly
Plugin URI: http://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
*/

Replacing the above code block with your own information rebrands the Hello Dolly, albeit the function of the plugin remains unchanged.

/*
Plugin Name: Aloha Dude jQuery
Description: Quick adaptation of a plugin from the <strong>Hello, Dolly</strong> plugin. Loads JS files properly as outlined in the WordPress Codex.
Author: Hawaii Dude
Version: 1.0.1
*/

Turning to the functions of the plugin, we find:

function hello_dolly_get_lyric() {
  /** These are the lyrics to Hello Dolly */
  $lyrics = "Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
So, take her wrap, fellas
Find her an empty lap, fellas
Dolly'll never go away again
Hello, Dolly
Well, hello, Dolly
It's so nice to have you back where you belong
You're lookin' swell, Dolly
I can tell, Dolly
You're still glowin', you're still crowin'
You're still goin' strong
We feel the room swayin'
While the band's playin'
One of your old favourite songs from way back when
Golly, gee, fellas
Find her a vacant knee, fellas
Dolly'll never go away
Dolly'll never go away
Dolly'll never go away again";

  // Here we split it into lines
  $lyrics = explode( "\n", $lyrics );

  // And then randomly choose a line
  return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] );
}

// This just echoes the chosen line, we'll position it later
function hello_dolly() {
  $chosen = hello_dolly_get_lyric();
  echo "<p id='dolly'>$chosen</p>";
}

// Now we set that function up to execute when the admin_notices action is called
add_action( 'admin_notices', 'hello_dolly' );

// We need some CSS to position the paragraph
function dolly_css() {
  // This makes sure that the positioning is also good for right-to-left languages
  $x = is_rtl() ? 'left' : 'right';

  echo "
  <style type='text/css'>
  #dolly {
    float: $x;
    padding-$x: 15px;
    padding-top: 5px;		
    margin: 0;
    font-size: 11px;
  }
  </style>
  ";
}

add_action( 'admin_head', 'dolly_css' );

The plugin consists of three functions and two action hooks. The first function function hello_dolly_get_lyric() is aptly titled and in accordance with the clean code philosophy it describes the purpose of the function. In this case, the lyrics of the song are assigned to the variable $lyrics. This function does not have its own action hook, rather it is called by the second function to do its thing.

Since the first function is returning a value, the second function can take this value and assign it to the variable $chosen. Given that functions are essentially independent islands of code, it’s necessary to call the first function from within the second function in order for it to be acted upon. The second function will take the randomized single line delivered by the first function and echo (print) it out in the area of the dashboard reserved for admin notices.

WordPress knows to do this by the action hook add_action( 'admin_notices', 'hello_dolly' ); in line 46 above. Looking closely at the syntax of this action, we see a typical function call in php with a named function followed by parentheses. Notice that when the function name consists of more than one word, the words are delineated by an underscore (_) and not a hyphen (-). Within the parentheses of the action, two elements are united in the fashion of what makes WordPress beautiful: a standard WordPress hook, the first argument in the parentheses, is told to render the second argument, a custom element of the plugin.

The third and final function of the plugin function dolly_css() helps position the given lyric in the admin area. Although this method of adding CSS to a page isn’t considered a best practice of WordPress, the amount of CSS is minimal and the age of the plugin likely warrants overlooking for nostalgic purposes.

Turning back to the question at hand in the support forum, and now that we understand how a simple plugin can work, we can easily modify the Hello Dolly plugin to suit our needs. You’ll recall we’ve already modified the commented code block at the top of the php file. The next thing we can do is delete the first function completely. By this I mean deleting the lines beginning with the line with the function name and the opening curly brace down to the closing curly brace, represented above from lines 1-37.

Rather than deleting the second function of Hello Dolly I renamed two arguments in the action hook to suit the needs of the new plugin. I then replaced the contents of the curly braces with the code that we were wanting to achieve as outlined in the Codex section for enqueuing scripts.

Finally, I rendered the third function useless by commenting out the action hook that would have triggered the function. While it’s not a best practice to leave fallow code within a plugin like this, I let it remain for illustration purposes.

/*
Plugin Name: Aloha Dude jQuery
Description: Quick adaptation of a plugin from the <strong>Hello, Dolly</strong> plugin. Loads JS files properly as outlined in the WordPress Codex.
Author: Hawaii Dude
Version: 1.0.1
*/
// Now we set that function up to execute when the admin_notices action is called
add_action( 'wp_enqueue_scripts', 'aloha_dude' );
function aloha_dude() {
  wp_register_script( 'dude-jquery', plugins_url( 'dude-jquery.js', __FILE__ ), array( 'jquery' ), null, true );
  wp_enqueue_script( 'dude-jquery' );
  wp_register_script( 'jquery.ui.touch-punch.min', '//cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.2/jquery.ui.touch-punch.min.js', array( 'jquery' ), null, true );
  wp_enqueue_script( 'jquery.ui.touch-punch.min' );
}
// add_action( 'admin_head', 'dolly_css' );
function dolly_css() {
  echo "
  <style type='text/css'>
  #dolly {
    float: $x;
    padding-$x: 15px;
    padding-top: 5px;
    margin: 0;
    font-size: 11px;
  }
  </style>
  ";
}

In this specific example above, I recommended that the hello-dolly.php be renamed and moved into a folder of the same name. The questioner also had a custom piece of code that they wanted enqueued, I chose to create a separate file and saved it in the newly created plugin folder. While there are many different, even better, ways to achieve the same results, this should help you understand what’s involved with creating a plugin and set you on your way to trying this on your own. For a somewhat more formalized view of the plugin we created, check out and download it from my Github page.

source: Can you recommend a good plugin to add Custom Jquery and Scripts

Leave a Reply

Your email address will not be published. Required fields are marked *