Social Bookmarking with WordPress Plugin

[ Share this article ]
Share this page via Facebook, Twitter or LinkedIn.
[ Send this article ]
[ Save this article ]
by Vladimir Prelovac | February 2009 | AJAX Content Management Open Source Web Development WordPress
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.
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
WordPress Plugin Development: Beginner's Guide
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.
  1. 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.
  2. 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
    */
    ?>
  3. 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);
    }
    ?>
  4. Upload your plugin file to the wp-content/plugins folder on your server using your FTP client.
  5. Go to your WordPress Plugins admin panel. You should now see your plugin listed among other plugins:
    WordPress Plugin Development: Beginner's Guide
  6. 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

  1. 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","<"))
  2. 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).

WordPress Plugin Development: Beginner's Guide

WordPress Plugin Development: Beginner's Guide Build powerful, interactive plug-ins for your blog and to share online

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.
  1. 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.'&amp;
    title='.$title.'&amp;bodytext='.$text.'">Digg This</a>';
    }
  2. 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(); ?>
  3. With the default WordPress theme, this change will look something like this (you can also refer to the following image):
  4. After you save the theme file, your blog posts will now automatically have the Digg This link shown after the content:
  5. 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
&raquo;</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.'&amp;
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://seoustaad.blogspot.com/ that will have all the details we need in order to implement our Digg functionality.
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://seoustaad.blogspot.com/.

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://yourwebsite/yourstoryurl/storypagedetails.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
search.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.

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 Development: Beginner's Guide

WordPress Plugin Development: Beginner's Guide Build powerful, interactive plug-ins for your blog and to share online

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.
  1. 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.'&amp;
    title='.$title.'&amp;bodytext='.$text.'">Digg This</a>';
    }
    <b>/* Add Digg link to the end of the post */
    function WPDiggThis_ContentFilter($content)
    {
    return $content.WPDiggThis_Link();
    }</b>
  2. Use the post content hook to automatically call our new function:
    add_filter('the_content', 'WPDiggThis_ContentFilter');
  3. 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(']]>', ']]&gt;', $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://seoustaad.blogspot.com/.
WordPress Action Reference : http://seoustaad.blogspot.com/.

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.
  1. 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);
    }
  2. 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();
    }
  3. Digg button now shows at the beginning of the single post page.
    WordPress Plugin Development: Beginner's Guide

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/Conditional_Tags

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://seoustaad.blogspot.com/) 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;