:: Plugin

Share/Bookmark

Get-the-image-link: Developing a simple WordPress Plugin

One of the really cool things about WordPress is that extending its functionality is a breeze. Think up a new feature and more often-than-not, someone has already written a plugin for it. With plugin installation now possible within the admin panel – things couldn’t be easier. You can search for, download, install and upgrade plugins without leaving the browser. Gone are the days of downloading, unzipping and messing with the command line on a remote server.

So, why did I end up writing a WordPress plugin? It all began with choosing a theme ….

Choosing a magazine style theme

I wanted to use a magazine style theme for this blog. I use K2 for all my other WordPress blogs and have been quite happy with it. However, the visual dazzle of recent magazine style themes left K2 a little wanting. Besides, most of K2s unique features like widget control were now standard in WordPress. I was impressed by the Hamasaki theme, developed by Nurudin Jauhari, on Aral Balkan’s blog. However, the elements were a little too large for my taste and the prominent place given to the most recent post was not to my liking. In contrast, Jauhari had another magazine style theme called hijiriah (demo) that I took a liking to instantly.

There are some excellent features in this theme. The money features for me were:

  • Built-in ad support ( a nice way to link to my other resources ).
  • Dynamic hierarchical navigation menu based on categories ( structured  access to eclectic subject matter ).
  • Auto generated image for each post ( pain free way to add some visual interest to the blog page ).

Auto generating an image for each post

I must say that this is the singular feature that really sold me on this theme. Images are generated automatically using a custom version of the Get the Image plugin developed by Justin Tadlock. This plugin is like a cascading image seeker. It also degrades gracefully. The following image seeking sequence is from the plugin README file.

  1. Looks for an image by custom field.
  2. If no image is found, it grabs an image attached to your post.
  3. If no image is attached, it can extract an image from your post content.
  4. If no image is found at this point, it will default to an image you set.

The Get the Image plugin has a function called get-the-image that returns the image element ( img tag ) for the auto generated image. A feature that is lacking is flexible image sizing ( you can only choose from predetermined sizes ).  To scale the image to a custom size, the hijriah theme uses an image resizing script called timthumb. This is the whole reason for customizing/hacking the plugin.

The custom version of Get the Image that shipped with hijriah was based on version 0.3. The customization was a simple hack to add an additional function to the plugin called get-the-link that returned the URL of the chosen image for the post ( as opposed to the whole image element ). For some reason, a similar function that existed in Get the Image was now deprecated (probably due to a very good reason unknown to me). The URL to the image chosen by the hacked Get the Image plugin was passed to the timthumb script for resizing and eventually displayed on the blog page.

Another issue was that version 0.3 of  Get the Image had a bug that prevented it from returning an image specified by a custom thumbnail field. Version 0.3.1 fixed this issue.

Upgrading plugins broke image auto generation

Of course, upgrading the Get the Image plugin to 0.3.1 overwrote the hacked version and the hijriah theme was left without an implementation for the template tag get-the-link.

Modifying the code in the hijriah theme ( I was using a child theme ) to substitute get-the-link tag with the get_the_image tag seemed a little too complicated due to the resizing issue. The other option was to write a new plugin that implemented the get-the-link function.

This was a beginning of my sojourn into plugin development…

Writing a plugin to implement the get-the-link template tag

Template tags are used within WordPress theme templates to display information dynamically. It is really nothing more than a call to a function internal to WordPress or externally implemented in a plugin or functions.php file. In the case of the hijriah theme, the get-the-link tag is required in the index.php template file.

The purpose of the new plugin clear and simple. Implement the get-the-link function by calling the get_the_image function in the  Get the Image plugin. I just have to use regex to extract the src attribute from the image element and return it. Simple right? Well, there were a few important things that I had to learn first.

Important stuff about plugins

This is my first attempt at writing a plugin for WordPress. I had to dispel some preconceived ideas.

It’s been awhile since I did any coding in PHP. Coming from my recent ActionScript 3 background and dabbling extensively in OOP and design patterns I thought the new plugin could simply extend the  Get the Image plugin class and override a method or two. But, noooo! I quickly realized what I was up against as my PHP started to come back.

WordPress has a nice modular architecture, but it is not modular in the OOP sense. Here is the definition of a plugin from the WordPress Codex.

A WordPress Plugin is a program, or a set of one or more functions, written in the PHP scripting language, that adds a specific set of features or services to the WordPress weblog, which can be seamlessly integrated with the weblog using access points and methods provided by the WordPress Plugin Application Program Interface (API).

Forget about looking for a class to extend. All the plugins I looked at were collections of functions. Here are some things I learned about WordPress plugins that may be useful for a newbie like myself.

The bar to entry is very low

It was surprising how easy it was to get WordPress to recognize a new plugin. This is a testament to the simplicity of the plugin architecture in WordPress. All you need is to create a new PHP file inside the plugins folder in your WordPress installation and write a comment block on it. Although not a requirement, it is always a good idea to put your plugin files inside a folder. The comment is the plugin information header.

plugin_file

You can now go into the WordPress admin panel and activate it (from the inactive plugins list). You will now see the plugin activated. Of course it doesn’t do anything, but that was incredibly easy!

Turing on the plugin from the Admin Panel

Activate the plugin from the Admin Panel

Plugins are just a collection of functions

The best way to learn how to write a plugin is by studying other plugins. Good starting point are akismet and the hello dolly plugins that are included in the default installation. You will quickly see that most plugins have no class definitions, but they are just a collection of functions.

Plugins can take two forms:

  1. Plugin as a library.
  2. Plugin as a dependency injector.
1. Plugin as library

This is the simplest form of a plugin. A library is simply a collection of functions. The client, a WordPress template in this case, can call the functions. Each function call does some work and returns control to the client.

Template tags are calls to WordPress functions that do something or return some value back to a template. For example,  the bloginfo template tag is a function implemented within WordPress and returns information about the blog based on passed parameters. The ‘name‘ parameter, shown below,  returns the name of the blog.

bloginfo('name');

Custom template tags can be implemented in plugins. This is a super easy way to extend WordPress functionality. All you need to do is implement a function in your plugin with the name of a template tag you come up with (make sure it is unique – more on this later). The following figure shows the index.php template calling the get-the-image template tag. The get-the-image function is implemented in the Get the Image plugin.

plugin1

2. Plugin as dependency injector

This is a more powerful method of extending the functionality of WordPress. Instead of waiting for the template to call the plugin function, the plugin injects the function into the template. Dependency injection using plugins is called hooks in WordPress. There are two types of functions that can be injected or hooked into wordpress: Actions and Filters.

Action functions can be hooked into specific events in WordPress. That means, the function is called or triggered by a specific WordPress event. For example, you can write an action function that informs different search engines when a new article is posted. The  plugin function will hook into the publish_post event. The events that can trigger an action function are numerous. Refer to the Plugin API/Action Reference for the list.

Filter functions can be hooked into WordPress  to pass content through the function before being output to the web page. For example, if you want to filter out profanity in comments, write a function that takes the comment text as a parameter and returns the clean content. Now you can hook this filter function to the comment_text filter hook so that it is called before comment text is published on the page. Refer to the Plugin API/Filter Reference for the list of filter hooks.

I won’t go into detail on writing plugins as dependency injectors. The plugin API documentation provides a good introduction. A good example on how to write action functions is to take a look at the hello dolly plugin. The book on WordPress Plugin Development by Vladimir Prevolac is quite good and explains action and filter functions very well ( check out the sample chapter ). Above all, download some plugins and take a look at the code – you will learn some interesting techniques.

Choose plugin and function names carefully

Make sure you use a unique name for your plugin and its function names. PHP  and WordPress don’t take kindly to duplicate function names. The plugin will just not load and you will be left wondering what happened. Searching the WordPress plugin directory before settling on a name is not a bad idea. The dash ‘-’ is the recommended separator for words in the filenames and function names for plugins.

Make sure the plugin function exists before you call it

This is also known as:

Looking for a black cat in a dark alley that isn’t there

This is most important for library type plugins that are called directly from templates. The template doesn’t know if the plugin exists or if it is activated. Therefore, it is a good idea to first check if the function is available before calling it from a template. The PHP statement in the template should be of the form:

if( function_exists('get-the-image') ) { get-the-image(); }

The tag function  ’get-the-link‘ will only be called if it exists. There is a tight coupling between the template tag and the plugin where the function is implemented. You need to manually add the tag to the new theme templates if you switch themes.

One of the big advantages of injector type plugins is that the hooks are created at runtime. The template files don’t have to be modified to call the functions. In fact, the template doesn’t know anything about the plugins or the hooks. Therefore, themes can be switched without requiring any changes in the template files.

Get the Image Link plugin

Let’s get back to the issue at hand. The purpose of the new plugin is to implement the get-the-link template tag by calling the get_the_image function in the  Get the Image plugin. We need to return the URL of the image as opposed to the image element.

It is a good idea to take a look at the README file for the Get the Image plugin before proceeding. First thing to note is that the function takes query string style parameters (as opposed to function style parameters). Query string style is desirable when a function has many parameters. The second issue to note is the ‘echo’ parameter which is set to true by default. This causes the function to echo the image element text to the output buffer inside the function. We need to set this to false.

The plugin will consist of one function called get-the-link that calls get-the-image in the Get the Image plugin. It then parses the image element to extract the src attribute using regexp and returns it.

function get_the_link($args = array())
{
	if (function_exists('get_the_image'))
	{
		$args = wp_parse_args($args);
		$args['echo'] = false; // prevent echo output
 
		$imageElement = get_the_image($args);
		$pattern = '/src=(['"])?(.*?)\1/i';
		preg_match($pattern, $imageElement, $matches);
 
		return $matches[2];
	}
}

You can now call the get-the-link template tag from a template and pass it as a parameter to the timthumb script for resizing. Look at the timthumb.php comment block for parameters and usage. The timthumb.php file is included in the hijriah theme.

I must say that writing a library type plugin was much simple than I thought. So, don’t hesitate to give it a try as the more you learn, the more comfortable you will be about customizing WordPress. I learned a lot about theme development during this process and now feel comfortable enough to develop a custom theme. I’ll write about that experience in a future post.

Download the Plugin

download_btn


  • Share/Bookmark

21 Comments

  1. Jauhari says:

    Get The Image is nicely plugin by Justin. And after on the latest version 0.3.1 and up buit in more feature, so I choose to little bit tweak the plugin than I created new plugins. I am not PHP Expert, so I only make some modification and make get the image plugin work with thimthumb.

    I was do it without worries and I was packaged with my Pro Pemuda and Hijriah new version :)

    Thank for using my hijriah and give alternate way ;)

  2. Chandima Cumaranatunge says:

    Hi Jauhari,
    Thanks for the note. Your PHP looks pretty good to me and your theme is one of the best I’ve seen (liked it enough to buy the pro version). I learned a lot about templates and themes by studying how hijriah works.

    I do realize that you had to tweak get-the-image and this post was not meant to be critical of that at all. Please feel free to use this little plugin, or just the code, if you need to (even for the pro version of hijriah).

    I searched for documentation and examples of plugins calling other plugins but didn’t find any. So, I’m not sure if there is a better way to call another plugin. I do know that regex can be a little slow, so calling the get-the-image-link plugin multiple times on a page will lead to some lag when loading the thumbnails.

    Looking forward to more theme inspiration from you.

  3. Bill Sanders says:

    Hey Chandima,

    That’s a very nice post on the WS plugin.

    Take care,
    Bill

  4. Ted says:

    How do you call the get-the-link in a template? Should work?

  5. Chandima Cumaranatunge says:

    Hi Ted, This was my first attempt at writing a plugin and I had some misconceptions about how the get-the-image plugin worked. It does have the facility to resize images, so get-the-image-link plugin is unnecessary for the most part (unless you just want the image URL for some reason).

    To create an image tag, use the following code in a template within the loop:

    <?php get_the_image('image_scan=true&height=100&width=100&default_image=/images/default_image.jpg'); ?>

    Substitute the proper URL for the default image.

  6. Ted says:

    Thanks for the quick reply, Chandima. Actually, getting the image URL is precisely what I need. I’m trying to use a theme that employs the timthumb script to resize images. Only problem, it doesn’t work properly in WordPress MU.

    I was attempting to use get-the-image, but the problem is that the way the theme is styled, I need to be able to grab just the image url, not the full html to display it.

    Hope that makes sense. If you could clarify how to get get-the-image-link to render just the url, I’d be very grateful.

  7. Chandima Cumaranatunge says:

    Here you go:

    <?php echo get_the_link('custom_key=Thumbnail&default_size=medium&image_scan=true&
    default_image=/defaultimageloc/image.gif');  ?>

    The above should echo the URL. I think you can specify any one of the get-the-image params and it should work as expected.

    I’m not using the Hijriah theme anymore but it feeds this URL to the Tim thumb script like so:

    <img src="<?php echo bloginfo('tem
    plate_url'); ?>/thumb.php?src=<?php echo get_the_link('custom_key=Thumbnail,My Thumbnail&default_size=medium&image_scan=true&
    default_image='.$nonono);  ?>&amp;h=<?php if ( get_option('jm_image_height') <> "" ) { echo get_option('jm_image_height'); } 
    else { ?>165<?php } ?>&amp;w=<?php if ( get_option('jm_thumb_height') <> "" ) { echo get_option('jm_thumb_width'); } else { ?
    >190<?php } ?>&amp;zc=1&amp;q=90" class="lastimage" alt="<?php the_title(); ?>"  />

    The above has some variables and theme options that are defined elsewhere. The Tim Thumb script is in the theme root directory and is called thumb.php.

  8. Ted says:

    Thank you, thank you. That works like a charm.

  9. Padam says:

    I would like to know, how can I get the link we posted together with image while posting an article. We are asked to insert Link url while attaching the image with our post. I would like to know the function to get that attacthed url.

    Thanks

  10. Chandima Cumaranatunge says:

    Hi Padam, I’m not sure if I understand the context you are using this plugin, but if you want the source URL and the image displayed just make two function calls. One call to get_the_link() to get the source URL of the image and another to get_the_image() to echo the image tag. Please let me know if I misunderstood your question.

  11. Padam says:

    Ok let me clarify myself. While we are attaching image on our post from admin we are also asked to give Link Url, which is optional. And we are redirected to the link (we posted in Link URL) when we click on that image. I also wanna do the same in your plugin. Your plugin is great, everything works and I wanna make a link (to link that we posted together with image while attaching image in our post) in image from your plugin.

  12. danni says:

    I would also like to know how to get the Link Url from the image. I would like to pull a specific url from the image propeties (”Link Url”) so that the image can link to an external url and not the post it sits in.

  13. Chandima Cumaranatunge says:

    @danni you will have to pull it from the post custom fields and put an anchor tag around the thumbnail image in the template. Look at the docs to access custom fields.

    http://codex.wordpress.org/Custom_Fields

  14. michelle mabardy says:

    Ok, I’m so sorry to ask this but I cannot find specific instructions anywhere. I’m using the hijriah free version and I cannot get the “get the image” plugin to work. And I would like to use the get the image link plug in as well but one at a time I guess. I see in your post that you say for this them, the code goes into the index file. But exactly where? Anywhere? Ok. Also, do I post this code …

    or do I need to alter this at all. I want to use this in the simplest way. Just take the first picture from a post and use it as a thumbnail on the index page. Please help. I’m not a developer but I do have some web/internet/code skills. Thank you for your help.

  15. Chandima Cumaranatunge says:

    Hi Michelle, things should work out-of-the-box in the free hijriah theme. The first image of each post will be displayed on the home page as a thumbnail with the excerpt. If that is not working add a custom field to one of the blog posts.

    1. Edit blog post on the admin side
    2. Scroll down to the Custom Fields area.
    3. Select “Thumbnail” for the name field and enter the full URL in the value field.

    Now you should get this image as the thumbnail for the post excerpt.

    If this doesn’t work then you may have updated the get-the-timage plugin in your wordpress install. This breaks the thumbnail functionality as described in my post. You can fix this by going back to the original version os the get-the-image plugin that came with the hijriah theme.

  16. michelle mabardy says:

    So I re-installed the older version of the plugin that came with the theme and it gets the images just fine but now I get “The function has been deprecated. You need to update your template file calls to get_the_image()”
    At the beginning of every post. I’ve looked online to see how to fix this but I cannot find the right solution.

    Please tell me what I have to change in my code.

    This is what my code looks like. There are two places on the index.php file where I have inserted it.
    —————————————

    ———————————-

    Also wondering about the color scheme. Any way to get it to be gray or multi colors?

    Please help. Thank you very much.

    Michelle

  17. Chandima Cumaranatunge says:

    Michelle , try to suppress warnings. You will have to edit the index.php template file. Get to it from:

    Site Admin > Appearance – Editor

    Now click on the “Main Index Template” (index.php) from the template file list on the right.

    Add the following in a new line before the get_header() php block at the top.

    < ?php error_reporting(E_ERROR); ?>

    Click on the “Update File” button and warnings should be suppressed.

  18. michelle mabardy says:

    Hi thank you for your help. I did what you suggested and it did not work. Could you please suggest something else. My site is http://www.bazaarorganic.com , you can see what’s happening. Also, this is my code

  19. michelle mabardy says:

    The code didnt come through in the last post. this is what i have as you suggested in the inex file.

    ——–

    —————-

  20. Hi there,

    I have been sending you and nurudin emails and I have not been getting any response. At one point, I would send him the email and you would respond. I’m not sure how this is working but i need a response from someone. I was asking for help with the ad placement and I was also still getting the deprecated image error on some of the inner pages. But, now, there is no site at all. I had set up a user acct for you guys (a second one) and I really need to know if anyone had gone in and done anything. If so, that is fine, I just really need to know. Now I have to do the whole thing over. I’m sure I am going to need a little help and the last email that I sent was last week with still no response. Can you please tell me what is going on? Why are my emails not being responded to. Why do you respond when I send emails to him at times. I really would like my $ back if this theme is not going to work for me. $50 is a lot of money these days and I dont need to be wasting it. THank you.

  21. [...] post: Get-the-image-link: Developing a simple WordPress Plugin Tags: development, php-echo, plugin, [...]

Leave a Comment