Developing my first WordPress plugin

It’s only couple of weeks that I’m using WordPress (actively!) and it’s been quite some time I last used PHP. There was a time when I was really comfortable with PHP, but that’s been oh so long ago. I’m all in Python nowadays. No stupid endless  curly brackets, or semicolons and the nice indentation is enforced… Ok, ok, it’s just me ranting, because I spent nearly 30 mins trying to figure out what’s wrong with my code. It appeared to be a missing $ in front of my variable name. How lame could that be?…

Right, back to business. So I decided to write a WordPress plugin. There were few reasons I wanted to do that:

  • See how difficult it is and what WordPress looks like under the hood
  • Since I’m using WP, which is a PHP shop I needed to remind myself how PHP looks like
  • Get some more publicity and bump up the Google rating (that’ll never hurt, will it?)

So, I remembered seeing this neat trick of reversing, or flipping over text by replacing regular ASCII latin characters with Unicode ones that resemble a mirror image of the original ones. There are numerous websites out there on the wild internets that would swallow your piece of texts and then spit out same text, but flipped over.

pǝsɹǝʌǝɹ uǝǝq sɐɥ ʇı ɹǝʇɟɐ ǝʞıʃ ʞooʃ pʃnoʍ ʇxǝʇ ǝɥʇ ʍoɥ sı ǝɹǝH

As you can see it is still text information, no magic with images or anything like that. You can select, copy-paste, etc.

So, I thought, right, let’s see if there was someone smart who has created a plugin for WordPress that would do this. Not that I’m a big fan of flipped over text, but just to make sure that I’m not reinventing the wheel. At the end of the day, what’s the point in creating something that’s already been build. If such plugin existed, I would have had to think of something else. Lucky for me, no one has yet created anything like it.

So, simple idea, just what I need to warm up.

First things first, go and read official manual from WordPress about how to develop plugins. It’s a really good manual, and everyone developing a plugin must read it. Or read it if you feel you need more details in following my manual… :)

All plugins go into /wp-content/plugins/ directory in your WordPress installation. Each plugin has it’s own directory, but this isn’t a strict requirement, but if you’re not creating a directory for your plugin, it must be just a single PHP file. I’d advise to create a directory for your plugin.

Right, this is how I saw me implementing this: user types in any text in the post (or page, or comment, or even excerpt) and encloses any text he/she wants to flip over in my new (made up) tags, just like that:

<upsidedown>your text</upsidedown>

Because WordPress does some clever validation of the text and only certain tags are allowed, I had to include this code in my plugin to declare my new tags as valid ones:

if (!CUSTOM_TAGS) {
    // allow new tag in the posts
    $allowedposttags['upsidedown'] = array();
    // ... and also in the comments
    $allowedtags['upsidedown'] = array();
}

Next thing is to register new filter function with WordPress. Hold on, what is this filter function? Filter function is a function that WordPress calls and passes contents of the post to it. Filter function can do anything it likes to the text and then spits is back to WordPress engine. WordPress will then pass the result to another filter, and so on and on until there are no more filter registered. Each filter get a priority flag assigned, and those with priority 0 will get executed before those that have priority 10. By default each filter gets priority 6 assigned to them.

Right, going back to my filters, let’s register them:

add_filter('the_content', 'flip_text_upside_down_filter');
add_filter('the_excerpt', 'flip_text_upside_down_filter');
add_filter('comment_text', 'flip_text_upside_down_filter');

As you can see, I register my filter with three types of content: post (or page), excerpt and comment.

Next thing is to define the filter function:

function flip_text_upside_down_filter($content)
{
    return preg_replace_callback(
        '/\s*<upsidedown>(.*)<\/upsidedown>/siU',
        'convert_to_upsidedown_unicode',
        $content
    );
}

WordPress is going to call it with a parameter that contains content text in it. I pass the contents to PHP function preg_replace_callback, which matches the regular expression (any text in between my tags) and calls another function with the contents of the regular expression match (hope that makes sense to you, if not, read the sentence again, repeat until you got it… :) ).
Finally, a function that actually does the conversion. Which is pretty simple – go through all characters and replace them with matching Unicode chars from the table. I’m not including the whole table here, you can download source code from WordPress plugins directory (in fact, if you install the plugin – you’ll have the sourcecode in your plugins/ directory):

function convert_to_upsidedown_unicode($match)
{
    // conversion table
    $flipTable = array(
...
    )
    $origStr = strrev($match[1]);
    $newStr = ' ';
    for ($i = 0; $i < strlen($origStr); $i++) {
        $ch = $origStr[$i];
        if (array_key_exists($ch, $flipTable)) {
            $newStr .= $flipTable[$ch];
        } else {
            $newStr .= $ch;
        }
    }
    return $newStr;
}

This is it. Well, ok nearly it. You still need to do the boring bit, ie put a formal header so WP recognises your plugin code (put this, replacing what’s necessary accordingly):

/*
Plugin Name: Upside Down Text
Plugin URI: http://www.grenadepod.com/projects/upside-down-text-plugin-for-wordpress/
Description: This plugin allows to "flip" any section of text upside down
Version: 1.1.0
Author: Grenadepod
Author URI: http://www.grenadepod.com
*/

Now you can activate the plugin from your WP admin console, and start typing text that everyone struggles to read.

Sooner or later you’ll notice that the implementation is not ideal. When you switch over to visual editor (which I use most of the time) and then back to HTML editor, all “new” tags are gone. This is because the editor does not know about them and so it removes them. Solution was to type in text in Visual (if you prefer to use it) then switch to HTML and place tags where needed. Save without switching back, and publish.

This wasn’t really nice, and I wasn’t going to get lots of users with this approach. Some nice soul on WordPress forum suggested to have a look at Shortcode API. This API allows plugin to register shortcode that looks like: [somethinghere]content[/somethinghere], and passes all content back to your function. And this would be immune to switching between editors issue.

So I decided to make a second release of the plugin, where shortcodes are supported alongside with tags. And in fact using shortcodes not only allows me to type them in directly in the Visual editor, but also coding is simpler, I don’t need to do any regexp magic.

Register my new shortcode:

add_shortcode('upsidedown', 'flip_text_upside_down_shortcode');

And define what function to call:

function flip_text_upside_down_shortcode($atts, $content=null)
{
    return convert_to_upsidedown_unicode(array('', $content));
}

As you can see, I’m reusing same character conversion function, so the changes were minimal.

All seems to be working quite fine, at the end of the day, what can go wrong with only few lines of code?…

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Live
  • Netvibes
  • NewsVine
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Bookmarks

Related posts:

  1. Securing WordPress
  2. Essential WordPress plugins
  3. Use SSH to upgrade WordPress plugins automatically