Gaining benefits from plugins
Saturday
Apr 25, 2009
There is an interesting comment stream going on over at OMNINOGGIN at the moment. Thaya has released another version of his excellent plugin WP Greet Box. As well as some new functionality the update adds a box to the dashboard which contains the titles, and links to, the last three WordPress development posts he has posted on his blog. In essence it is just a feedreader pointed at his feed.
He has done this to try and inspire a little extra traffic to his blog, but a few people have taken against this because they were surprised by it. It isn’t an opt-in, but you can easily turn it off in the same way as anything else on the Dashboard.
I can see why plugin authors want to do this kind of thing. It is getting harder and harder to stand out in the WordPress community and so it is harder to gain as much benefit. I am not sure how much benefit this will bring, but as he isn’t doing anything but telling us, in a passive way, what is happening on his blog, I don’t really mind it.
What do you think? Is it reasonable for plugin authors to try and show us more about their site (these plugins are free after all) or should the plugin just do its thing and leave us alone?
The master plan
Saturday
Apr 25, 2009
It’s been a long time, I shouldn’t have left you, without a strong rhyme to step to.
Eric B & Rakim - I know you got soul (1987)
Every now and again it pays to take a break from blogging, from technology, from everything, and concentrate on something else. Call it a break, a recharge, whatever, it really helps focus you on where you should be. And that is what I’ve done.
Now that I’m back I’ve made some decisions about the direction of Fun with WordPress, and where I want to be, so I have made a few changes.
The biggest immediate change is to the theme, or rather the themes that I will use. My last theme was complex and, because it was designed to work with Habari and WordPress, complicated to change. In general that is fine, because I have the knowledge, but it doesn’t reflect the experience of WordPress that most people have. Given the amount of criticism I heap on WordPress and the assumptions I make about the experience that other users have, I think it is important that I have the same experience.
As a result of that decision I am now using a great theme called WPUnlimited. Importantly I am using the options and tools that come built into the theme and not diving into the pages and code to change things. I am still trying to find the look that I want, but I don’t think it will take me too long. I will write a bit more about my experience with it, over the next few days.
With the change of theme also comes a change of comment system. I have been using Disqus for a while now but it started to lose its sheen and I am now back to the standard comment system. I will write a little about that soon as well.
Another change I have made, for the same reason, is to move another one of my blogs, a blog that I only use sporadically, called Fun with Opinions to WordPress.com. This will be my first ever foray into the world of WordPress.com but I think it is probably important for me to understand the differences.
There are other philosophical differences in the way I intend to approach the blog which will become evident over time, but for now I am back in the room and excited about what people are doing with WordPress.
Themes: A little more conversation a little less action, baby!
Sunday
Apr 19, 2009
I think the problem with WordPress (and indeed all blog and cms platform) themes is that there is a little bit too much doing, and not enough talking. Recently we have had quite a number of theme frameworks, most of which are very good, we’ve had debates about how plugins should pass on styles to the content they add into a theme, and we’ve had discussions about replacing the default theme, with suggestions about what that replacement should be that are entirely contradictory. Ultimately I think what is needed is consistency, not evolution, or even revolution. Themes may be the one place where intelligent design is the answer.
When you sit down to do some serious programming you do several things. You plan your inputs and outputs, design tests to make sure that each function produces the results that are expected in the form they are expected, and plan the overall architecture. As you progress you solve problems and turn the solutions into patterns that can be reused or improved up.
In this way you produce schemes that produce solid and consistent code that is easily readable, understandable, modifiable, and extensible, and this must surely be the goal for themes, and for the way that themes and widgets interact.
If this all sounds a little abstract then don’t worry, it needn’t be. But, this is where conversation and communication come in. There is no benefit in everyone producing their own theme solutions if each solution requires widgets to behave in a different way, and every, and for someone extending that theme to do so in a different way. We need to stop acting and start talking.
Let me give you some more practical examples:
- (x)HTML 4/5 — There are many reasons for choosing one over the other. They don’t really matter. It is more important that a theme, plugin, or widget, can predict the environment it will insert into.
- Widget / plugin styling — It is fine to ask where the CSS should go, but a better question should be how to define what kind of output it is1, and therefore how all outputs of that type will be structured so they can be pre-styled by the theme author2.
- Child themes — Will they be used or not, and if so what do we do about modifying child themes themselves?
- Simplicity versus complexity — What level of knowledge should be required to make changes? Should you have to learn the theme first, or can all themes have a relatively standard HTML base.
- Modularity — How much functionality should be built into a theme in the first place? Should a theme be just the presentation with a lot of hooks, and all the functionality outsourced to plugins that can be easily switched out?.
These are just the points that occur to me on the spot, but I hope you can see that diversity, while good in some cases, can also be seriously detrimental. Consider how much better and easier theming could be for the end users if a little consistency was available.
If WordPress needs to stay balanced at the top of the pyramid then paradigm diversity in the theme space3 needs to be curtailed. I strongly believe that the early days of themeing, despite the fact that its multiple Kubrick rip-offs took a lot of wading through to find the gems, was massively enhanced by so many themes being based on the underlying Kubrick structure. We knew what to expect, how to change it, and more importantly it wasn’t a huge leap to produce our own themes. We need to replace Kubrick soon, but we need to replace it with a consensus, not with the pure weight of diversity.
Footnotes
1: For example, is it a menu element, a styled content block, an unstyled content block, a multiple-post navigation control.
2: It needn’t even be styled by the author, for example a standard set of styles for horizonal navigation should be available as part of a default stylesheet. Given this sort of thing some plugins wouldn’t even need their own CSS.
3: Yes, that is a horrible sentence that drips with the stench of marketing, but it says what I mean so it stays.
How to build the new next generation theme
Thursday
Mar 26, 2009
How complex, or complicated, does a theme need to be to offer all the possible solutions that you want? I think it is possible to do it very very simply, with only one template page.
There are three widget based plugins which I think provide functionality so powerful that it is possible to create one index.php file with dynamic sidebars in key positions and to use widgets for everything else. Here are those plugins:
Fun with theme widgets
This is one of mine, and by far the simplest and least impressive of the three, but, it provides an incredibly simple way for theme builders or individuals to create their own widgets out of snippets of code.
You can find out more about Fun with theme widgets here
Query posts widget plugin
This plugin by Justin Tadlock is most excellent. It allows you to include a list of posts by selecting the selection criteria. I see no reason why this shouldn’t be used instead of hard coding the page lists into the theme itself. If it supports paging and templates then even better.
You can read more about Justin Tadlock’s Query post widget plugin here.
Widget context
Kaspars widget context plugin adds the option to any widget to choose when it is displayed, i.e. home page, single post pages, when the URL contains certain characters etc. This is the killer plugin as, combined with the two above, it is no longer necessary to create individual post pages. Simply decide which widgets should go where.
You can read more about Kaspar’s Widget Context plugin here.
Presetting widgets
It isn’t a plugin, but any theme using these combinations of plugins and widgets really needs the option to preset some widgets. Ptah Dunbar recently wrote a post explaining how to preset widgets from within a theme so this is a post well worth checking out.
Are these widgets the next step toward the ultimate WordPress theme system? I don’t know; what do you think?
Book Review: WordPress Plugin Development
Friday
Mar 20, 2009
I recieved my copy of WordPress Plug-in Development (Beginner’s Guide) by Vladimir Prelovac a few days ago and have been reading through it with great interest. I have long thought that this kind of book was due, in fact I even considered writing one myself, so I am really glad that one has finally arrived.
This is a Beginner’s guide, but even so there is a lot in this book. This isn’t a book on first principles alone so even if you’ve created your own plugins before there is likely to be something in this for you. The cover of the book contains the following words which seem to sum it up pretty well:
Learn by doing: less theory, more results.
The book is organised around the development of six plugins. With each chapter a new plugin is started, developed and explained. None of the plugins are simple so this really is a book for someone who actively wants to learn. Vladimir has clearly decided that you can get a ‘Hello World!’ plugin tutorial from anywhere so, while he does explain what you will need to develop plugins, for example, where you can get free tools, and does include the basic ‘Hello World’ skills in the first tutorial, he kicks off the book at a fast pace.
The benefit of this fast paced style is that every plugin is guininely useful and contains important skills and a lot of information. Each chapter also gives suggestions for how you can customise the plugin so you can do more than just follow along.
By the second plugin Vladimir will have you diving into JQuery and AJAX, in the third you’ll be creating Widgets, and by the end you’ll be integrating flickr into the WordPress admin, and creating your own post types.
When I first heard about the book there were two things that I really wanted to find out: What plugin architecture would Vladimir recommend in the book and where would he draw the line between ease of understanding and promoting best practices. Teaching someone to write a plugin is fairly easy, but teaching them to write plugins well is very difficult.
The chapters do a great job of easing the reader into the best practice concepts. In the first plugin the reader is told how to build the plugin without messing around too much. He still suggests version checking at this point, but the basic lesson is very simple. It isn’t until the third plugin that he introduces the concept of classes in plugins, giving plenty of time to get used to the core concepts first but ultimately steering the reader toward the best method.
As early as the second plugin Vliadimir is talking about security and using nonces and concepts such as caching and localisation aren’t far behind. In fact, this book contains the best explanation I have read so far about using software to create the necessary files for localisation. I can honestly say that after just a brief skim through the section on localisation I feel that I know more than from all the other online guides I have read.
Finally, Vladimir doesn’t stop at the coding aspects. He goes on to talk about distribution, promotion, providing support, using SVN (Using ToroiseSVN) as an example (again a really good introduction to it).
Downsides?
There is only one downside to the book and it was always going to be inevitable. That is that WordPress development tends to move at a swift pace. Already there are some developments, such as the improved widget code, that aren’t in the book. I don’t think this is a big issue though. Learning to develop for WordPress using this book will provide enough understanding to cope with the changes.
I wonder whether Vladimir is slaving over a second edition already? Perhaps Jeff can ask him when he appears on WordPress Weekly in a few weeks time. (27th March I think).
Conclusion
You can surely tell that I like this book. I do. I would go so far as to say that if you aspire to develop for WordPress you should own this book and if you already develop for WordPress, you should also own it, even if it is just to confirm what you already know.
WordPress Plug-in Development (Beginner’s Guide) is well prepared, well written, easy to use, and I heartily recommend it.
Replacing WordPress features
Sunday
Mar 15, 2009
What would it take for you to use a plugin that replaced a core feature of WordPress?
That is the question that has occurred to me this lunch time. You see, WordPress 2.8 has a new way of creating widgets, and a UI upgrade is on the cards, but what if it wasn’t? Would you use a plugin that replaced the core feature?
Now, I’m using widgets as an example because it is a particularly conspicuous set of functions. It is accessed by themes, by other plugins, and the core even creates widgets to include in it. So using a replacement system would mean choosing to forego any existing content.
This about what that means for a moment. If you have a theme, and you want to use new widgets, you need to modify the theme. If you have plugins they will need a rewrite, and the basic widgets wouldn’t work. It is fair, however, to assume that the writer of such a replacement would create new basic widgets such as the text widgets, PHP widget, calendar, search, links, and so on.
Obviously the functionality offered needs to be better; that’s a given, but how much better would it need to be?
I also wonder what kind of dilemma it would create for the core squad. There is something new and better out there but using it means removing something else that already works, is very popular, and is in constant use. By using this new plugin in favour of the original functionality you would be complicit in this dilemma.
It’s interesting don’t you think?
Social Bookmarking with WordPress Plugin
Thursday
Mar 12, 2009
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:
- Creating a new plugin and having it displayed in the plugins admin panel
- Checking the WordPress version and control activation of the plugin
- Accessing API features—for example the title and permalink URL of each post
- Using WordPress hooks to execute your plugin code when it's needed
- Using conditional tags to control the flow of your plugins
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!
Plugging in your first plugin
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.
Time for action — Create your first plugin
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.
- Create a file called wp-digg-this.php in your favorite text editor. It is common practice to use the plugin name as the name for the plugin file, with dashes '-' instead of spaces.
- Next, add a plugin information header. The format of the header is always the same and you only need to change the relevant information for every plugin:
<?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 */ ?> - Now add the code to check the WordPress version:
/* 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); } ?> - Upload your plugin file to the wp-content/plugins folder on your server using your FTP client.
- Go to your WordPress Plugins admin panel. You should now see your plugin listed among other plugins:

- This means we have just completed the necessary steps to display our plugin in WordPress. Our plugin can be even activated now—although it does not do anything useful (yet).
What just happened?
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.
The plugin information header
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.
Checking WordPress versions
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.
Checking the plugin
You can go ahead and activate the plugin. The plugin will be activated but will do nothing at this moment.
Time for Action — Testing the version check
- Deactivate the plugin and change the version check code to a higher version. For example, replace 2.6 with 5.0.
if (version_compare($wp_version,"
5.0","<")) - Re-upload the plugin and try to activate it again. You will see a WordPress error and a message from the plugin:

What just happened?
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.
Have a go Hero
We created a basic plugin that you can now customize.
- Change the plugin description to include HTML formatting (add bold or links to the description).
- Test your plugin to see what happens if you have two plugins with the same name (upload a copy of the file under a different name).
Displaying a Digg button
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.
Time for Action — Implement a Digg link
Let's create a function to display a Digg submit link using information from the post.
- Add a function to our plugin to display a Digg link:
/* 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>'; } - Open your theme's single.php file and add a call to our function just below the line with the_content(). If you are not sure how to do this, see the forthcoming section on "Editing the theme files".
<?php if (function_exists(WPDiggThis_
Link)) echo WPDiggThis_ Link(); ?> - With the default WordPress theme, this change will look something like this (you can also refer to the following image):

- After you save the theme file, your blog posts will now automatically have the Digg This link shown after the content:

- Clicking the link will take the user directly to the Digg site, with all the required information already filled in:

Well done! You have created your first working WordPress plugin!
What just happened?
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.
Using the Digg API
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.
Submit URL:
http://digg.com/submit?url=
Submit URL Details:
- url=example.com
Maximum length is 255 characters
Story URL should be unique and devoid of session or user-specific data
Please URL-encode all strings as appropriate. For example:
http%3A%2F%2Fyourwebsite%2Fyourstoryurl% 2Fstorypagedetails.html - title=TITLE
Maximum length is 75 characters
Please also URL-encode the story title - bodytext=DESCRIPTION
Maximum length is 350 characters
Please also URL-encode the body text
Using this information, we are able to create a valid link for the Digg service from the information available in our post.
Acquiring post information
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.
Post permalink URL
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.
Editing the theme files
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 |
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.
Have a go Hero
Our plugin already has useful functionality. Try to customize it by:
- Calling our Digg link function from different places in the theme template, for example, before the content or after the tags are displayed (look for the_tags() line in the template).
- Adding the function to other theme templates such as the main index file and archive pages to display the Digg links on the home page and blog archives as well.
- Using the get_the_title() and get_the_content() functions to obtain post title and content instead of using the $post variable.
WordPress plugin hooks
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:
- If you want to change to a different theme, the plugin will stop working until you edit the new theme.
- If you want to distribute your plugin to other people, they can't just install it and activate it; they have to change their theme files too.
- If you change the function name, you need to alter the theme files again.
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.
Time for Action — Use a filter hook
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 function that we will use to hook to the content filter:
// 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> - Use the post content hook to automatically call our new function:
add_filter('the_content', 'WPDiggThis_ContentFilter'); - Remove the references to our function from the theme template as we no longer need them. Leaving them would have the effect of showing the link twice.
The end result is now the same, but we now control the appearance of the link directly from our plugin.
What just happened?
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 hooks
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:
- Action hooks: These are triggered by WordPress events, for example, when someone creates a post or writes a comment.
- Filter hooks: These are used to modify WordPress content on the fly, like title or content of the post as it is being served to the user.
Filter 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] );
- filter_hook: One of the filter hooks provided by WordPress.
- filter_function_name: A function used to process the content provided by the filter_hook.
- priority: An optional parameter, which specifies the execution order of functions. The default value is 10 if several functions apply to the same filter hook, functions with a lower priority number execute first, while the functions with the same priority will execute in the order in which they were added to the filter.
- accepted_args: An optional parameter, which specifies how many arguments your function can accept. The default value is 1. The accepted_args parameter is used for hooks that pass more than one argument.
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.
Action Hooks
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] );
- action_hook: The name of the hook provided by WordPress.
- action_function_name: The name of the function you want to use to handle the event.
- priority: An optional parameter, which specifies the execution order of functions. The default value is 10. If several functions apply to the same filter hook, then functions with lower priority numbers will execute first, while the functions with the same priority will execute in the order in which they were added.
- accepted_args: It is optional and specifies how many arguments your function can accept. The default value is 1 and is used for hooks that pass more than one argument.
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.
Practical filters and actions examples
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.
Upper case titles
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);
Mailing list
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');
Changing core WordPress functionality
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/
Have a go Hero
Our filter function now controls the behaviour of a Digg link. Try these exercises:
- Place a Digg link before the post content by prepending the output of our function to the content
- Add the current date to your page title in the browser window by using the wp_title filter and the date() PHP function
- Capitalize the first letter of the users' comments in case they forgot to do so. Use the comment_text filter and the ucfirst() PHP function
Adding a Digg button using JavaScript code
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.
Time for Action — Implement a Digg button
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.
- Create a new function for displaying a nice Digg button using JavaScript code.
/* 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); } - Modify our filter function to include the Digg button for single posts and pages, and a Digg link for all the other pages:
/* 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(); } - Digg button now shows at the beginning of the single post page.

What just happened?
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>";
Conditional Tags
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/
Styling the output
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.
Time for Action — Use CSS to position the button
Using CSS styles, we will move the button to the right of the post.
- We will accomplish this by first encapsulating the button in a <div> element. Then we will add a CSS style to this element stating that the button should appear on the right, with a left margin towards the text of 10 pixels.
// 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; - The result of applying this simple CSS code is that Digg Button now shows to the right of the post.

What just happened?
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.
Have a go Hero
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.
- You can use the digg_bgcolor, digg_skin, digg_window parameters of Digg JavaScript to control the appearance of the button (refer to http://digg.com/tools/
integrate ) - Use CSS to play with the layout of the button
- Create similar plugins that will allow the user to submit content to sites such as Stumble Upon or Reddit
Summary
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:
- Creating a plugin: How to fill in the informati on header and create a simple plugin template
- Checking WordPress version: How to check that our plugin is compatible with the user’s version of WordPress
- Modifying theme files: How to safely add functions to the theme files when we need to
- Accessing post information: Different ways of obtaining data from the post such as title, permalink and content
- Using WordPress hooks: How to use actions and filters to get things done from within our plugin (and not modifying the theme for instance)
WPUnlimited - The ultimate WordPress theme?
Tuesday
Mar 10, 2009
I have little doubt that most of you will have heard of WP Unlimited, David Peralty’s premium theme offering. David has chosen to brand it as ‘The ultimate WordPress theme’; I couldn’t let that one go, so I’ve spent the last few days playing around with it so I could give you my considered opinion of it.
Firstly, I think the choice of tag-line is brave. For me the tag-line conjures up images of some kind of complex behemoth, so it was with some trepidation that I installed it. The reality is, I am happy to report, quite the opposite. I found it really easy to get going with, more so than many of the premium themes I have tried in the past. On the surface this theme seems really simple and that is certainly one of my key criteria for ultimateness. I should however start from the start.
The first thing I found when I unzipped it was a really handy PDF instruction book. 20 pages of explanation later left me feeling pretty confident that I would be able to do what I wanted with this theme. Blogging isn’t rocket science but it was nice to have a simple explanation of the interface and the tools.
The first time I activated the theme though I found the the thing I like most; out of all the fancy layout, styling, and SEO tools, the thing I really like is how simple the base theme is. Themes, premium themes especially, have been getting glossier and more graphical, and while that is fine, it can make it hard to retune. David has turned his back on all that and presented a good solid, neutral, base from which to start customising. He assumes you want to change it. A lot.
I am genuinely tempted to add my header image in and use the base theme as is. Really.
My preference for white aside, I think the area that will most impress purchasers of this theme is that David seems to have given a significant amount of thought to what bloggers, rather than developers, actually want in a theme. Of all the themes I have used this really does feel the most focussed on the kinds of people I know that use WordPress within the community. Let me give some examples that stand out for me:
On the first page of the options is a box to enter code that will be displayed to visitors if they have arrived via a search engine, a feedburner url box, a box to add content to the end of your RSS feeds (i.e. copyright notices), and the option to include social networking links such as Digg, Sphinn, Facebook, and StumbleUpon.
On the second page you can turn on or off the blog title and tag-line independently of each other, select the content-sidebar configuration you want and, importantly, change the width of these.
The penultimate panel is something I haven’t seen before that I think will really go down well. In the theme they are called Hooks. They let you add content into certain pre-defined places. They sound like PHP enabled text widgets, but are actually more specific than that; for example, if you want to add specific content above or below the content of every post, or between each post, then these can do that for you. I really like this idea and I’m curious to see how it is used, so if you have used these then drop a note in the comments to your blog.
I can’t leave this section without mentioning the style customisation. The theme is designed with several core areas of colour. Using the design tab (which even has some preset colour and type schemes ), you can change things like the background colour, text colour, border colour, border size, padding, link colour and font family.

A lot of these things were previously available in plugin form. You can argue the merits of deciding to bundle the functionality within the theme, but having them all available as part of theme feels right and after trying this out I can’t help but feel that this is the right move, for this theme at least.
So far I haven’t really mentioned the code and I don’t really intend to. That isn’t the point of this theme. I should point out however, that the theme doesn’t really reinvent anything so if you want add HTML manually or change the HTML you can. The theme uses the standard plugin files (Which is a very good thing). You won’t get any surprises if you want to go digging.
Niggles
Of course I do have a few niggles; it is only natural. The first is that I made a lot of changes in the admin page, changing each set of options as I went. When I got to the option to upload an image I did so and the rest of my changes got lost at that point. It was forseable, in fact I knew it was going to happen, but a warning, or perhaps a javascript alert to ask if I want to save first might be useful.
The second is really a problem I have with every theme out there. I just don’t feel that anyone has fully engaged with menus and I don’t think much of the accepted method of selecting the pages you don’t want to appear in the menu. There is nothing wrong with that, but it isn’t the dynamic menu manager that I think is possible. There is scope for a revolution in menu’s and it hasn’t happened here. I can’t really blame that on this particular theme though.
Conclusion
This theme does a lot for you with very little effort. It is a really nice intermediate step between complex frameworks and glossy premium themes. I can’t say that this is the ultimate WordPress theme. I can say though that, in my opinion, the ultimate theme is yet to be built, and perhaps never will be. Perhaps the ultimate theme isn’t even a theme. All that aside though, don’t let that put you off trying this theme. I really like it, and I think you might as well.
What this theme does is get the basics right and then leave you alone. In my book this is a really good approach to themes and, in a year when everyone is predicting that child themes and frameworks will be the big thing, I applaud WP Unlimited for doing the opposite and keeping it real.
I feel quite happy recommending this theme so check out the full features page, demo, and video tutorials to find out more.
Reset your widgets
Wednesday
Mar 4, 2009
I have written a few plugins that use widgets, and had a few support requests when some widgets disappear, often when upgrading or turning off a plugin. Justin Tadlock as now released a solution: a plugin that resets your widgets to remove them from all your sidebars.
I think it is a great idea, you can check out the widget reset plugin at Justin’s site.
Auto Cycle Fun with Sidebar Tabs
Thursday
Feb 19, 2009
A few weeks ago Thaya of Omninoggin produced an add on to my Fun with Sidebar Tabs plugin. He asked my if I would update the plugin to include that code and I agreed, but I haven’t done it and here’s why.
I did actually go ahead and add in Thaya’s code because I thought his addition was really great; however, the first time I tried it on a clean(ish) install it didn’t work perfectly. He had anticipated this and provided comments in the code where changes could be made to turn off a particular feature. Since then I have debated whether to commit the change and I have decided not to.
I stopped supporting Fun with Sidebar Tabs because it has a serious flaw. It relies on CSS specificity within the theme not overriding the CSS settings and it relies on previous Javascript being bug free to run. Those two things cause problems and in return requests for help which I just don’t have the time to respond to in a timely fashion.
I debated including the new code as an option, just switch the files over and you have it, I debated just including it and letting users modify it in the code if they wanted to turn off a particular function, but ultimately I decided that I didn’t want to risk providing an updated that prevented the plugin working where people already used it, I didn’t think that many users would have the confidence to change the files themselves, that most users would update the plugin automatically without checking what was in it, and I also didn’t want to give the impression that I was making updates to the plugin.
As I said, I did make the change, so if you want to download the updated javascript file you can do so here, but I won’t be committing it to the repository for the reasons I’ve explained. All credit for the update goes to Thaya who is producing some really great plugins at the moment and had the wherewithall to make the extra code for this one.



