Creating a Simple WordPress Plugin.

To start this series of tutorials off on how to create a wordpress plugin, I’m going to show you how to create a simple “Tweet Me” button that you can put on any any post or page, and looks like the following.

[bhtweetthis]

Its a real working version of the plugin, try it and see what happens..

Ok, lets make it.

A few years ago, WordPress introduced the concept of short code into their system and it it has made it so easy to generate plugin like this one.

Basically a short code is some text wrapped in square brackets “[abc]” and the text inside the brackets tells the plugin what to do at that point in the post.

So, for out plugin we will be generating a short code, that looks like [bhtweetthis]

So without more messing about, lets make it:

First lets make the header section of the plugin, it will look like this :

<?php
/*
Plugin Name: [BH] TweetThis
Plugin URI: http://www.brucehearder.com/creating-a-simple-wordpress-plugin
Description: Display A Tweet This button on Your Blog Page or Post using a short code
Version: 20 August 2010
Author: Bruce Hearder
Author URI: http://www.websitesecrets101.com
*/
?>

The information shown here, is the info that will get displayed on your plugins page in your blog when you install this plugin.

Now, to get the shortcode to work.

WordPress uses “things” called hooks, this allows your code to “hook” into the main wordpress code base and get called at the right time.

We are going to use one of those hooks called “add_shortcode”. This links the add_shortcode hook with a function that we want to call to display our info.

add_shortcode('bhtweetthis', 'processShortcode');

This means, whenever the shortcode of bhtweetthis is found, it will call the function ‘processShortcode”

Now lets make the function:
function processShortcode($atts,$content=null)
{
global $post;
$title = $post->post_title;
$link = get_permalink($post->ID);
$shortlink = @file_get_contents('http://tinyurl.com/api-create.php?url='.$link);
if ($shortlink!='')
{
$twitterurl='http://twitter.com/home?status='.urlencode($title).'%20'.$shortlink;
$thelink = '< a target="_new" href="'.$twitterurl.'">< img class="size-full" src="/tweet-this.jpg" alt="" width="101" height="27" >';
return $thelink;
}
else
{
return '';
}
}

Close off the file with a
? >

and save into your /wp-content/plugins/ directory.

You now have a simple “tweet me” plugin.

If you have any questions or thoughts, please leave them as comments below.

Post By Bruce Hearder (21 Posts)

Bruce published and manages the content on BruceHearder.com He's a software developer, technology enthusiast, web developer and love to squueze the most out of websites. You can lean more about him on Google+

Connect