A primer on writing WordPress plugins

WordPress is a great (well, in my opinion the greatest) weblog software ever, although it can even be used as a content management system (CMS). It’s vast community of users provided lots of themes and extensions to the software, and WordPress itself is being improved all the time, be it functionality or bug-fixes.

Suppose you wanted it to extent yourself, say by writing a plugin, how would you go about? Let me tell you.

First of all, plugins are kept in a specific place in the WordPress directory structure, namely in webroot/wp-content/plugins. More complex plugins are consolidated in subdirectories, but simple ones, like we’re going to write here, can be put in the plugins directory itself.

Let’s start simple and create a plugin that does absolutely nothing, but still is considered a plugin.

The plugin I eventually describe here will provide a ‘read more’ link for excerpts, since they don’t have that by default.

< ?php
/*
Plugin Name: WP Excerpt More
Version: 0.1
Description: This plugin adds a Read More link to your excerpts.
Author: Peter Boosten
Author URI: http://www.boosten.org
Plugin URL: http://www.boosten.org
*/
?>

Save this to a file called myfirstplugin.php (or any other name you desire) and put it into the plugin directory. If you switch to the admin dashboard of your WordPress and choose plugins from the sidebar, you’ll actually see the plugin, although deactivated, together with all information you filled in above (Well, you’ll see my name if you copied the exact information above). You can even activate the plugin.

Let’s enhance it a bit. Suppose you wanted the plugin to check the version of WordPress it minimal needs (remember I wrote that WordPress gets improved constantly, and some functionality isn’t available in older versions), then all you have to do is to add the following bit of code:

< ?php
/*
Plugin Name: WP Excerpt More
Version: 0.2
Description: This plugin adds a Read More link to your excerpts.
Author: Peter Boosten
Author URI: http://www.boosten.org
Plugin URL: http://www.boosten.org
*/
 
/* Version check */
global $wp_version;
 
$exit_msg='WP Excerpt More requires Wordpress 2.6 or newer. Please update!';
 
if (version_compare($wp_version,"2.6","<"))
{
	exit ($exit_msg);
}
 
?>

WordPress provides us with all kind of useful information, like the version of the software you’re currently running. This version is communicated through a variable called $wp_version. Just compare that to the version you think minimal is required (2.6 in the above example) and tell the plugin to exit if this doesn’t meet your requirements. The admin panel will respond with the message you defined in $exit_msg, and the plugin cannot be activated. You can try that yourself if you raise your requirement to a version higher than the current version you’re running.

Oke, now for the real stuff. Our aim in the plugin was to add a read more link for excerpt, so lets create one.

< ?php
/*
Plugin Name: WP Excerpt More
Version: 0.3
Description: This plugin adds a Read More link to your excerpts.
Author: Peter Boosten
Author URI: http://www.boosten.org
Plugin URL: http://www.boosten.org
*/
 
/* Version check */
global $wp_version;
 
$exit_msg='WP Excerpt More requires Wordpress 2.6 or newer. Please update!';
 
if (version_compare($wp_version,"2.6","<"))
{
	exit ($exit_msg);
}
 
function WPReadMore_Link()
{
	global $post;
 
	// get the URL to the post
	$link=get_permalink($post->ID);
 
	// get the post title
	$title=$post->post_title;
 
	// create a Read More and return it
	return '&lt;a href="'.$link. '" title="'.$title.'"&gt;Read more&lt;/a&gt;';
}
 
 
?>

That’s it. You’ve created a fully functional, and mostly useful plugin. I tell you below how to use it, but let’s focus on the content of the plugin.

We’ve created a function called WPReadMore_Link, which needs no parameters to run. It gets however (again) valuable information from WordPress, namely an array called $post. This array is only available in combination with a post, so you’ll have to use the function defined in this plugin in the Loop. There are two things we want from that array, the permalink and the title of the post (the latter is not really needed, but it looks kinda cute).

This information is returned to WordPress, disguised as an anchor link, surrounding a text called ‘Read more’.

How would you make this link available in the loop?
Simply locate the place where ‘the_excerpt();’ is in the code, and just below it, write ‘WPReadMore_Link();’.

Now you’ll have a read more link below your excerpt. But wait, what if you would disable (or remove) the plugin again. You’ll be left with an error message of a not found function. You could do the following:

< ?php if (function_exists(WPReadMore_Link)) echo WPReadMore_Link(); ?>

instead of just ‘WPReadMore_Link();’.

No rocket science needed here: if the plugin is activated, then the function will exist and will be called whenever the code is parsed, otherwise it won’t.

In an ideal world, you don’t want to edit your theme to add this link, but you want the plugin to manage that for itself. For this purpose the kind guys (and gals of course) left us so called plugin hooks, through which we can extend the functionality of existing functions, or alter them altogether. For now we just want to add something, namely add a read more link at the end of the excerpt.

< ?php
/*
Plugin Name: WP Excerpt More
Version: 0.4
Description: This plugin adds a Read More link to your excerpts.
Author: Peter Boosten
Author URI: http://www.boosten.org
Plugin URL: http://www.boosten.org
*/
 
/* Version check */
global $wp_version;
 
$exit_msg='WP Excerpt More requires Wordpress 2.6 or newer. Please update!';
 
if (version_compare($wp_version,"2.6","<"))
{
	exit ($exit_msg);
}
 
function WPReadMore_Link()
{
	global $post;
 
	// get the URL to the post
	$link=get_permalink($post->ID);
 
	// get the post title
	$title=$post->post_title;
 
	// create a Read More and return it
	return '&lt;a href="'.$link. '" title="'.$title.'"&gt;Read more&lt;/a&gt;';
}
 
/* Add Read more to the end of the excerpt */
 
function WPReadMore_ContentFilter($excerpt)
{
	return $excerpt.WPReadMore_Link();
}
 
add_filter('the_excerpt','WPReadMore_ContentFilter');
 
?>

That’s it. If you remove the function call from the theme, and use the above code, you’ll still presented with a read more link. How does it work?

We’ve created a function called WPReadMore_ContentFilter($excerpt), which takes the excerpt text as parameter, and returns the same text, concatenated with whatever is returned by the WPReadMore_Link() function, in this case the read more link. You could reorder the output of this function, and have the read more link before the excerpt (which looks kinda odd, but hey, it’s your birthday party) by writing this return: return WPReadMore_Link().$excerpt;

The ‘add_filter’ function is the most important function: it hooks the WPReadMore_ContentFilter function into the the_excerpt function, so every time the_excerpt() is executed, our function is executed as well.

Just one thing to do, I guess:

< ?php
/*
Plugin Name: WP Excerpt More
Version: 0.5
Description: This plugin adds a Read More link to your excerpts.
Author: Peter Boosten
Author URI: http://www.boosten.org
Plugin URL: http://www.boosten.org
*/
 
/* Version check */
global $wp_version;
 
$exit_msg='WP Excerpt More requires Wordpress 2.6 or newer. Please update!';
 
if (version_compare($wp_version,"2.6","<"))
{
	exit ($exit_msg);
}
 
function WPReadMore_Link()
{
	global $post;
 
	// get the URL to the post
	$link=get_permalink($post->ID);
 
	// get the post title
	$title=$post->post_title;
 
	// create a Read More and return it
	return '&lt;a class="myreadmorelink" href="'.$link. '" title="'.$title.'"&gt;Read more&lt;/a&gt;';
}
 
/* Add Read more to the end of the excerpt */
 
function WPReadMore_ContentFilter($excerpt)
{
	return $excerpt.WPReadMore_Link();
}
 
add_filter('the_excerpt','WPReadMore_ContentFilter');
 
?>

The only thing I added was a class to the anchor link, since you want to have some styling possibilities afterwards, but you could also embed the anchor link in divs, if you wanted to.

That’s it folks, enjoy.

This entry was posted on Wednesday, September 2nd, 2009 at 9:12 pm and is filed under webpublishing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

15 Comments to A primer on writing WordPress plugins

  • [...] More: A primer on writing WordPress plugins | boosten.org [...]

  • [...] the previous article I described how easy it is to create a useful [...]

  • cubrikaska says:

    Maravillosamente! Gracias!

  • “Just a question what theme do you use? Is it a free template? Did you hire a freelancer to create this? “

  • [...] follows the same principle as filters and actions (used in plugins), in fact you could even write a plugin, where you define shortcodes (and I know several plugin [...]

  • sheepskin boots says:

    That is the best article i have seen,Thank you a lot

  • To be straight I full concord with Your substance.

  • Juegos says:

    I’m sure is a great article but I’m afraid is too much for me, I still prefer ready-made plugins :-)

  • Thank you for explaining this so clearly.

    I’m showing a list of pages under a section using code from: http://www.snilesh.com/resources/wordpress/wordpress-hacks-and-tricks/wordpress-show-title-and-excerpt-of-child-pages-on-parent-page/

    However I’m unsure how to change your plugin so that the Read more link to their correct pages. At the moment they link back to the page we’re on. Any help greatly appreciated!

    • Hi John,

      Thanks for your comment.

      The only thing I can think of at this moment (I would have to test) is that child pages are a bit tricky to the way the plugin is build, especially at this point:

      function WPReadMore_ContentFilter($excerpt)
      {
      return $excerpt.WPReadMore_Link();
      }

      add_filter(‘the_excerpt’,'WPReadMore_ContentFilter’);

      You could try to comment out the add_filter function, and call the following function directly, just after calling the_excerpt().

      WPReadMore_Link();

      Please let me know how that works out.

      • Hi Peter

        Thanks for replying, I found some code to improve the excerpt which allowed me to remove the [...] as follows: (Ps I hope comments allows code in the [ code ] format [/ code ])

        [code]
        function improved_trim_excerpt($text) {
        global $post;
        if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $text = preg_replace('@]*?>.*?@si', '', $text);
        $text = strip_tags($text, '');
        $excerpt_length = 30;
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
        array_pop($words);
        array_push($words, ' ');
        $text = implode(' ', $words);
        }
        }
        return $text;
        }

        remove_filter('get_the_excerpt', 'wp_trim_excerpt');
        add_filter('get_the_excerpt', 'improved_trim_excerpt');

        ?>
        [/code]

        Then in the loop I put in a read more link as follows:
        [code]

        <a href="guid; ?>" rel="bookmark" title="post_title; ?>">Read more
        [/code]

  • Tiberius14 says:

    Thank you. I have successfully used your useful tips to create my first plugin:
    http://www.tautologicalcode.net/wordpress-plugin-wp-really-simple-health/
    ciao
    Tiberius14

  • Roman says:

    Thanks, man! Great article.

  • Leave a Reply

    Spam Protection by WP-SpamFree