Vladimir Prelovac has written a book called WordPress Plugin Development (beginners guide). I plan on reviewing it here later on this week, however, while I’m waiting for the snail-man to rush me my copy I have an excerpt from the book below for you to take a look at.
In this article by Vladimir Prelovac, we will learn to create our first functional WordPress plugin and learn how to interact with the WordPress API (this is the WordPress interface to PHP) on the way. The knowledge you will gain in this article alone will allow you to write a lot of similar plugins. This article is extracted from the "WordPress Plugin Development" book.
Let's get moving! In this article, you will learn:
You will learn these by creating a Social Bookmarking type of plugin that adds a Digg button to each post on your blog

As you probably know, Digg is a very popular service for promoting interesting content on the Internet. The purpose of a Digg button on your blog is to make it easier for Digg users to vote for your article and also to bring in more visitors to your blog.
The plugin we'll create in this article will automatically insert the necessary code to each of your posts. So let's get started with WordPress plugin development!
Usually, the first step in plugin creation is coming up with a plugin name. We usually want to use a name that is associated with what the plugin does, so we will call this plugin, WP Digg This. WP is a common prefix used to name WordPress plugins.
To introduce the plugin to WordPress, we need to create a standard plugin header. This will always be the first piece of code in the plugin file and it is used to identify the plugin to WordPress.
In this example, we're going to write the code to register the plugin with WordPress, describe what the plugin does for the user, check whether it works on the currently installed version of WordPress, and to activate it.
<?php /* Plugin Name: WP Digg This Version: 0.1 Description: Automatically adds Digg This button to your posts. Author: Vladimir Prelovac Author URI: http://www.prelovac.com/vladimir Plugin URI: http://www.prelovac.com/vladimir/wordpress-plugins/ wp-digg-this */ ?>
/* Version check */ global $wp_version; $exit_msg='WP Digg This requires WordPress 2.5 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress ">Please update!</a>'; if (version_compare($wp_version," 2.5","<")) { exit ($exit_msg); } ?>

We created a working plugin template by using a plugin information header and the version check code. The plugin header allows the plugin to be identified and displayed properly in the plugins admin panel. The version check code will warn users of our plugin who have older WordPress versions to upgrade their WordPress installation and prevent compatibility problems.
To identify the plugin to WordPress, we need to include a plugin information header with each plugin.
The header is written as a PHP comment and contains several fields with important information.
This code alone is enough for the plugin to be registered, displayed in the admin panel and readied for activation.
If your future plugin has more than one PHP file, the plugin information should be placed only in your main file, the one which will include() or require() the other plugin PHP files.
To ensure that our plugin is not activated on incompatible WordPress versions, we will perform a simple WordPress version check at the very beginning of our code.
WordPress provides the global variable $wp_version that provides the current WordPress version in standard format. We can then use PHP function version_compare() to compare this and our required version for the plugin, using the following code:
if (version_compare($wp_version,"2.6","<")) { // do something if WordPress version is lower then 2.6 }
If we want to stop the execution of the plugin upon activation, we can use the exit() function with the error message we want to show.
In our case, we want to show the required version information and display the link to the WordPress upgrade site.
$exit_msg='WP Digg This requires WordPress 2.6 or newer. <a href="http://codex.wordpress.org/Upgrading_WordPress ">Please update!</a>'; if (version_compare($wp_version," 2.6","<")) { exit ($exit_msg); }
While being simple, this piece of code is also very effective. With the constant development of WordPress, and newer versions evolving relatively often, you can use version checking to prevent potential incompatibility problems.
The version number of your current WordPress installation can be found in the footer text of the admin menu. To begin with, you can use that version in your plugin version check (for example, 2.6).
Later, when you learn about WordPress versions and their differences, you'll be able to lower the version requirement to the minimal your plugin will be compatible with. This will allow your plugin to be used on more blogs, as not all blogs always use the latest version of WordPress.
You can go ahead and activate the plugin. The plugin will be activated but will do nothing at this moment.
if (version_compare($wp_version,"5.0","<"))

The version check fails and the plugin exits with our predefined error message. The same thing will happen to a user trying to use your plugin with outdated WordPress installation, requiring them to update to a newer version.
We created a basic plugin that you can now customize.
Now it's time to expand our plugin with concrete functionality and add a Digg link to every post on our blog.
In order to create a link we will need to extract post's permalink URL, title, and description. Luckily, WordPress provides us with a variety of ways to do this.
Let's create a function to display a Digg submit link using information from the post.
/* Show a Digg This link */
function WPDiggThis_Link()
{
global $post;
// get the URL to the post
$link=urlencode(get_permalink($post->ID));
// get the post title
$title=urlencode($post->post_title);
// get first 350 characters of post and strip it off
// HTML tags
$text=urlencode(substr(strip_tags($post->post_content),
0, 350));
// create a Digg link and return it
return '<a href="http://digg.com/submit?url='.$link.'& ;
title='.$title.'&bodytext='.$text.'">Digg This</a>';
}
<?php if (function_exists(WPDiggThis_Link)) echo WPDiggThis_ Link(); ?>



Well done! You have created your first working WordPress plugin!
When WordPress loads a post, the single.php template file from the currently active WordPress theme is ran. We added a line to this file that calls our plugin function WPDiggThis_Link() just after the content of the post is displayed:
<?php the_content('<p class="serif">Read the rest of this entry
»</p>'); ?>
<b><?php if (function_exists(WPDiggThis_Link)) echo WPDiggThis_
Link(); ?></b>
We use function_exists() to check our function because it exists only if our plugin is installed and activated. PHP will generate an error if we try to run a nonexistent function. But if we deactivate the plugin later, we don't want to cause errors with our theme. So, we make sure that the function exists before we attempt to run it.
Assuming that the plugin is present and activated, the WPDiggThis_Link() function from our plugin is ran. The first part of the following function gets information about our post and assigns it to variables:
/* Show a Digg This link */
function WPDiggThis_Link()
{
global $post;
// get the URL to the post
$link=urlencode(get_permalink($post->ID));
// get the post title
$title=urlencode($post->post_title);
// get first 350 characters of post and strip it off HTML tags
$text=urlencode(substr(strip_tags($post->post_content),
0, 350));
We use the urlencode() PHP function for all the parameters that we will pass to the final link. This will ensure that all the values are formatted properly.
The second part uses this information to construct a Digg submit link:
// create a Digg link and return it return '<a href="http://digg.com/submit?url='.$link.'& ; title='.$amp;title.'&bodytext='.$text.'">Digg This</a>'; }
It returns this HTML text so that it gets added to the WordPress output at the point where the function is called — just after the post is displayed. Therefore, the link appears right after each post—which is convenient for the user who has just finished reading the post.
Usually, when using the functionalities of third-party sites, as we are doing in our example with Digg, we would search for the API documentation first. Almost all the major sites have extensive documentation available to help developers use their services in an effective way.
Digg is no exception, and if you search the Internet for the digg button api you will find a page at http://digg.com/tools/
Digg allows us to use several different ways of using their service.

For the start, we will display just a Digg link. Later, we will expand it and also display a normal button.
Here is what the Digg documentation says about formatting a submit link.
http://digg.com/submit?url=
Using this information, we are able to create a valid link for the Digg service from the information available in our post.
WordPress provides a number of ways to get information about the current post.
One of them involves using the global variable $post, which stores all the relevant information for the current post. We have used it in our example to extract the post title and content, but it can also be used to get other information such as post category, status and so on.
WordPress also offers an array of functions we could have used to access post information such as get_the_title() and get_the_content().
The main difference between using these functions and accessing post data directly using $post variable is in the end information we get. The $post variable contains raw information about the post, just as the user wrote it. The functions mentioned above take the same raw information as a starting point, but could have the final output modified by external factors such as other active plugins.
You can browse through the wp-includes/post-template.php file of your WordPress installation to get a better understanding of the differences between using the $post variable and the WordPress provided functions.
In order to obtain post URL we used the get_permalink() WordPress function. This function accepts the post ID as a parameter, and as a result, returns post's actual URL on the blog. It will always return a valid URL to your post no matter what permalink structure your blog is using.
In our example, we had to edit our theme in order to place the Digg link under the post content. WordPress allows for easy theme editing through the built-in Theme Editor panel.
After selecting the theme you want to edit, you will be presented with a number of options. Every theme consists of various PHP template files, each covering different blog functionalities.
Here is a reference table detailing the most commonly used template files.
|
File |
PAGE |
DESCRIPTION |
|
index.php |
Main index file |
This is the main theme file; it is used to render any page as a replacement if the 'specialised' file listed below is missing |
|
home.php |
Home page |
Used to display contents of the home page of the blog, which usually includes a list of recent posts. |
|
single.php |
Single post |
Called when you click on a single post to display post comments; usually includes comments template at the end. |
|
page.php |
Page Template |
Same as single post, but is used for displaying pages |
|
archive.php |
Archives |
Displays blog archives, such as earlier posts, posts by month or categories. |
|
comments.php |
Comments |
Template responsible for showing user comments and the comment area for new comments |
|
header.php |
Header |
Outputs the header for every page, usually containing information such as title and navigation, and includes theme style sheets and so on |
|
footer.php |
Footer |
The footer of every page, usually containing copyright information and useful links |
|
searc h.php |
Search results |
This template is used to show search results for your blog; It is usually similar to archive.php but also includes information about the searched phrase |
|
sidebar.php |
Sidebar |
Shows the blog sidebar; if the theme supports widgets, it will also include widget support functions |
|
404.php |
404 file not found page |
Default page for showing missing (404) pages on your blog |
Always be careful when editing the theme files as any kind of mistake in your syntax can cause an error in displaying the page. It is therefore good practice to first backup theme files, so you can safely revert to them afterwards.
Quick reference
$post: A global WordPress variable containing information about the currently processed post.
get_permalink($post_id) : Returns the full URL to the post given by its ID (for example $post->ID).
function_exists($function): Helps the PHP function to check if the given function exists. It is useful in themes when we want to include our function.
urlencode($string): Helps the PHP function to properly format the parameters to be used in a URL query.
Our plugin already has useful functionality. Try to customize it by:
Our plugin now works fine, but there is a problem. In order to use it, we also have to edit the theme. This can be a real pain for all sorts of reasons:
We need some way to make the plugin work on its own, without the users having to change their themes or anything else.
Hooks come to the rescue, making it possible to display our Digg This button in our posts—without ever modifying our theme.
We will use the the_content filter hook to automatically add our Digg This link to the end of the post content. This will avoid the need for the users to edit their theme files if they want to use our plugin.
// create a Digg link and return it return '<a href="http://digg.com/submit?url='.$link.'& ; title='.$title.'&bodytext='.$text.'">Digg This</a>'; } <b>/* Add Digg link to the end of the post */ function WPDiggThis_ContentFilter($ content) { return $content.WPDiggThis_Link(); }</b>
add_filter('the_content', 'WPDiggThis_ContentFilter');
The end result is now the same, but we now control the appearance of the link directly from our plugin.
When we activate our plugin now, WordPress comes across and runs this line:
add_filter('the_content', 'WPDiggThis_ContentFilter');
This tells WordPress that every time it's going to display the content of a post or page, it should run it through our WPDiggThis_ContentFilter() function. We don't need to modify the theme file anymore — WordPress will make sure that the function runs at the required time.
When we load a post now, WordPress will automatically call our function:
/* Add Digg link to the end of the post */ function WPDiggThis_ContentFilter($content) { <b>return $content.WPDiggThis_Link();</ b> }
This function receives the post's content as a parameter, and returns the filtered content. In this case, our Digg link gets automatically appended to the end of the content.
WordPress provides a powerful mechanism for plugin functions to be called at the exact time when we need them. This functionality is accomplished by using the so called hooks.
Every time you call a page from your browser, the WordPress engine goes through every possible function it needs to render the requested page. Somewhere along the way, you can "hook" up your function and use it to affect the end result.
You do this by simply registering your function with a specified hook, allowing it to be called by WordPress at the right moment.
There are two types of WordPress hooks:
We learned that filter hooks (also referred to as simply 'filters') are functions that process WordPress content, whether it is about to be saved in the database or displayed in the user's browser. WordPress expects these functions to modify the content they get and return it.
In our case, we used the_content filter hook to modify the post content by appending a Digg link to it. We could also have placed the Digg link at the beginning of the post, or broken up the post and put it in the middle.
To set up a filter, we need to use the add_filter function:
add_filter ( 'filter_hook', 'filter_function_name' , [priority], [accepted_args] );
Here is an example list of filter hooks, which will help you to get a better understanding of what you can achieve using them.
|
Filter |
Description |
|
the_content |
Applied to the post content retrieved from the database prior to printing on the screen |
|
the_content_rss |
Applied to the post content prior to including in an RSS feed |
|
the_title |
Applied to the post title retrieved from the database prior to printing on the screen |
|
wp_title |
Applied to the blog page title before sending to the browser in the wp_title function |
|
comment_text |
Applied to the comment text before display on the screen by the comment_text function and in the admin menus |
|
get_categories |
Applied to the category list generated by the get_categories function |
|
the_permalink |
Applied to the permalink URL for a post prior to printing by the_permalink function |
|
autosave_interval |
Applied to the interval for auto-saving posts |
|
theme_root_uri |
Applied to the theme root directory URI returned by the get_theme_root_uri function |
Filter hooks can be removed using the remove_filter() function. It accepts the same arguments as add_filter(), and is useful if you want to replace some of the existing WordPress filters with your functions.
If you want to take a closer look at the default WordPress filters, you can find them in the wp-includesdefault-filters.php file of your WordPress installation.
It is important to remember that the filter function always receives some data and is responsible for returning the data, whether it modifies the data or not. Only if you want to disregard this data completely, can you return an empty value.
We use action hooks when we need to include specific functionalities every time a WordPress event triggers, for example when the user publishes a post or changes the theme.
WordPress does not ask for any information back from the action function, it simply notifies it that a certain event has happened, and that a function should respond to it in a desired way.
Action hooks are used in a way similar to the filter hooks. The syntax for setting up an action hooks is:
add_action ( 'action_hook', 'action_function_name', [priority], [accepted_args] );
The following table presents example action hooks provided by WordPress.
|
Action |
Description |
|
create_category |
Runs when a new category is created |
|
publish_post |
Runs when a post is published, or if it is edited and its status is "published" |
|
wp_blacklist_check |
Runs to check whether a comment should be blacklisted |
|
switch_theme |
Runs when the blog's theme is changed |
|
activate_(plugin_file_name) |
Runs when the plugin is first activated |
|
admin_head |
Runs in the HTML <head> section of the admin panel |
|
wp_head |
Runs when the template calls the wp_head function. This hook is generally placed near the top of a page template between <head> and </head> |
|
init |
Runs after WordPress has finished loading but before any headers are sent; it is useful for intercepting $_GET or $_POST triggers |
|
user_register |
Runs when a user's profile is first created |
Just as with filters, you can use the remove_action() function to remove currently registered actions.
Since understanding the power of filters and actions is very important for conquering WordPress plugin development, we will now examine a few more simple examples of their usage.
The hook function can be any registered function. In this case, we will pass the title of the post to strtoupper making all titles appear in upper case.
add_filter('the_title', strtoupper);
Actions provide a very powerful mechanism for automating tasks. Here is how to send a notification to a mailing list whenever there is an update on your blog.
function mailing_list($post_ID)
{
$list = 'john@somesite.com,becky@somesite.com ';
mail($list, 'My Blog Update',
'My blog has just been updated: '.get_settings('home'));
}
// Send notification with every new post and comment
add_action('publish_post', 'mailing_list');
add_action('comment_post', 'mailing_list');
Sometimes you may not be satisfied with the default WordPress functionalities. You may be tempted to modify the WordPress source code, but you should never do that. One of the main reason is that when you upgrade to a new version of WordPress the upgrade process could overwrite your changes.
Instead, try whenever possible to write a plugin and use actions and filters to change the desired functionality.
Let's say we want to change WordPress post excerpt handling. WordPress uses the wp_trim_excerpt() function with the get_the_excerpt filter responsible for processing the post excerpt. No problem, let's replace it with our own function, using the WordPress function as a starting point.
/* Create excerpt with 70 words and preserved HTML tags */
function my_wp_trim_excerpt($text)
{
if ( '' == $text )
{
$text = get_the_content('');
$text = apply_filters('the_content', $text);
$text = str_replace(']]>', ']]>', $text);
$excerpt_length = 70;
$words = explode(' ', $text, $excerpt_length + 1);
if (count($words) > $excerpt_length)
{
array_pop($words);
array_push($words, '[...]');
$text = implode(' ', $words);
}
}
return $text;
}
// remove WordPress default excerpt filter
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
// Add our custom filter with low priority
add_filter('get_the_excerpt', my_wp_trim_excerpt, 20);
These were just a few practical examples. You can do almost anything that crosses your mind using action and filter hooks in WordPress.
Sometimes, you can achieve the same result by using either the action or the filter hook.
For example, if you want to change the text of the post you can use publish_post action hook to change the post as it is being saved to the database. Alternatively, you can use the_content filter to change the text of the post as it is displayed in the browser window.
Although the result is the same, we accomplish the goal in different ways. In the first case, when using the action hook, the post itself will remain permanently changed, whereas using the filter hook will change the text everytime it is displayed. You will want to use the functionality more suitable for your needs.
Quick reference
add_filter ('filter_hook', 'filter_function_name', [priority], [accepted_args]): This is used to hook our function to the given filter.
add_action ('action_hook', 'action_function_name', [priority], [accepted_args]): This is used to hook our function to the given action.
remove_filter() and remove_action(): This is used to remove already assigned filters and actions.
the_content : This is a popular filter for the post content.(do not confuse with the_content() function, which is a template tag to display the content of a post in the theme)
WordPress Filter Reference: http://codex.wordpress.org/
WordPress Action Reference : http://codex.wordpress.org/
Our filter function now controls the behaviour of a Digg link. Try these exercises:
Our Digg link works fine for submitting the content, but isn't very pretty, and does not show the number of Diggs we received. That is why we need to use a standard Digg button.
This is accomplished by using a simple piece of JavaScript code provided by Digg, and passing it the necessary information.
Let us implement a Digg button, using information from the Digg API. We will use the newly created button on single posts, and keep the simple Digg link for all the other pages.
/* Return a Digg button */
function WPDiggThis_Button()
{
global $post;
// get the URL to the post
$link=js_escape(get_permalink($post->ID));
// get the post title
$title=js_escape($post->post_title);
// get the content
$text=js_escape(substr(strip_tags($post->post_content),
0, 350));
// create a Digg button and return it
$button="
<script type='text/javascript'>
digg_url = '$link';
digg_title = '$title';
digg_bodytext = '$text';
</script>
<script src='http://digg.com/tools/diggthis.js '
type='text/javascript'></script>"
return ($button);
}
/* Add Digg This to the post */ function WPDiggThis_ContentFilter($content) { // if on single post or page display the button if (is_single() || is_page()) return WPDiggThis_Button().$content; else return $content.WPDiggThis_Link(); }

WordPress will parse our content filter function according to the conditional statement we have added:
function WPDiggThis_ContentFilter($content) { // if on single post or page display the button if (is_single() || is_page()) return WPDiggThis_Button().$content;
This means that if the current viewed page is a single post or page, we will append our Digg button at the beginning of that post.
If we are viewing all the other pages on the blog (like for example the home page or archives) we will show the Digg This link instead.
if (is_single() || is_page()) return WPDiggThis_Button().$content; else return $content.WPDiggThis_Link(); }
The reason for doing so is that we do not want to clutter the home page of the blog with a lot of big yellow Digg buttons. So we just place a subtle link below the post instead. On single pages, we show the normal button using our new WPDiggThis_Button() function.
The first part is similar to our previous WPDiggThis_Link() function, and it acquires the necessary post information.
/* Return a Digg button */
function WPDiggThis_Button()
{
global $post;
// get the URL to the post
$link=js_escape(get_permalink($post->ID));
// get the post title
$title=js_escape($post->post_title);
// get the content
$text=js_escape(substr(strip_tags($post->post_content), 0, 350));
However in this case, we are treating all the information through the js_escape() WordPress function, which handles formatting of content for usage in JavaScript code. This includes handling of quotes, double quotes and line endings, and is necessary to make sure that our JavaScript code will work properly.
We then create a code using Digg API documentation for a JavaScript button:
// create a Digg button and return it $button=" <script type='text/javascript'> digg_url = '$link'; digg_title = '$title'; digg_bodytext = '$text'; </script> <script src='http://digg.com/tools/diggthis.js ' type='text/javascript'></script>";
We have used two functions in our example, is_single() and is_page(). These are WordPress conditional tags and are useful for determining the currently viewed page on the blog. We used them to determine if we want to display a button or just a link.
WordPress provides a number of conditional tags that can be used to control execution of your code depending on what the user is currently viewing.
Here is the reference table for some of the most popular conditional tags.
|
Tag |
RETURNS TRUE IF USER IS VIEWING |
|
is_home |
Blog home page |
|
is_admin |
Administration interface |
|
is_single |
Single post page |
|
is_page |
Blog page |
|
is_category |
Archives by category |
|
is_tag |
Archives by tag |
|
is_date |
Archives by date |
|
is_search |
Search results |
Conditional tags are used in a variety of ways. For example, is_single('15') checks whether the current page is a single post with ID 15. You can also check by title. is_page('About') checks if we are on the page with the title 'About'.
Quick reference
is_single(), is_page(): These are conditional tags to determine the nature of the currently viewed content
js_escape(): A WordPress function to properly escape the strings to be used in JavaScript code
WordPress Conditional Tags: http://codex.wordpress.org/
Our Digg button looks like it could use a better positioning, as the default one spoils the look of the theme. So, we will use CSS to reposition the button.
Cascading Style Sheets or CSS for short (http://www.w3.org/Style/CSS/) are a simple but powerful tool that allows web developers to add different styles to web presentations. They allow full control over the layout, size, and color of elements on a given page.
Using CSS styles, we will move the button to the right of the post.
// create a Digg button and return it $button=" <script type='text/javascript'> digg_url = '$link'; digg_title = '$title'; digg_bodytext = '$text'; </script> <script src='http://digg.com/tools/diggthis.js ' type='text/ javascript'></script>"; // encapsulate the button in a div $button=' <div style="float: right; margin-left: 10px; margin-bottom: 4px;"> '.$button.' </div>'; return $button;

We used CSS to move the button to a desired position. CSS is extremely useful for these kinds of tasks and is commonly used in WordPress development to enhance the user experience.
// encapsulate the button in a div $button=' <div style="float: right; margin-left: 10px; margin-bottom: 4px;"> '.$button.' </div>';
We have basically encapsulated our button in a <div> element and forced it to the right edge by using float: right CSS command inside a style tag.
We could further experiment with the placement of the button until we find the most satisfying solution.
For example, if we hook to the_title filter instead of the_content, and moved the button to the left , we would get the following result:

Certainly, having good CSS skills is a very valuable asset in WordPress plugin development.
Now that our button is finished, there are a lot of possible customizations you can make to the look or position of your button, using both built-in Digg options and CSS.
In this article, we created a working, useful, and attractive WordPress plugin from scratch. Our plugin now displays a fully functional Digg button.
We learned how to extract information using WordPress API and how to use CSS to improve the appearance of our plugin. We also investigated some more advanced WordPress functionalities such as hooks.
Specifically, we covered: