Using TimThumb with WordPress MU

A few days ago, I saw a post on Smashing Magazine outlining ten tips to give your WordPress blog a little more personality. While most of the tips don’t really apply to the blogs on which I’m currently working, tip number two piqued my interest.

Tip number two explains how to display a list of “related posts” at the bottom of each post, and tells you how to add icons to each of those related posts. Unfortunately, when I attempted to implement the tip on one of my WordPress MU blogs, I found that it didn’t work for a few reasons.

  1. The tip uses a meta element called “post-img” which, as I’ve found since attempting to implement the tip, isn’t a standard WordPress element.
  2. TimThumb doesn’t work with WordPress MU out-of-the-box.

So, I set out trying to figure out how I should implement the tip. Following are the results of my tinkering.

Post-Img Meta Element

As I mentioned, the “post-img” meta element is not something that WordPress (the regular version or the MU flavor) generates on its own. Instead, you need to create it yourself. The way I implemented post-img was to create a new “Custom Field” (on the “Add New Post” screen) called “post-img” (without the quotes, obviously).

Then, I used the WordPress uploader to upload an appropriate image to my server. Rather than inserting the image into the post, though, I copied the file URL and pasted it as the value of the new post-img custom field I created.

Then, for accessibility reasons, I created another custom field called “post-img-alt” to hold the value I plan to use in my alt tag wherever I show the post-img.

Using TimThumb with MU

I then set about trying to figure out how to get TimThumb working with WordPress MU. I posed a simple question on Twitter and got a little tip from @andrea_r. Andrea apparently runs a Web site with tips for WordPress MU users, so it was great to hear from her. Her response gave me a good place to start searching for information on WPMU functions, and after working on a few things and exchanging a little conversation with her, I found all of the pieces I needed to make TimThumb work.

For those of you that want to know why TimThumb doesn’t work with WPMU, you can read the article to which @andrea_r linked me when I told her I was working with TimThumb. I had already been working on my own solution by the time I read that article anyway, and found that my solution was a little more flexible, as it won’t break if the WPMU user changes the path to which files are uploaded for each individual blog. BinaryMoon’s article assumes that the WPMU administrator left everything set to the default parameters when the blog was set up. If you aren’t ever planning to create a WPMU blog with a custom upload path, BinaryMoon’s solution is perfectly usable. However, if there’s a remote possibility you might use a custom upload path (for instance, if you decided to use the same upload path for multiple blogs), you will need to adjust it the way I explain below.

Following is the code I developed using TimThumb with WPMU. The code below assumes that you saved timthumb.php inside of a directory called timthumb within your current theme’s directory.

<img src="<?php bloginfo('template_directory'); ?>/timthumb/timthumb.php?src=<?php echo get_current_site(1)->path; echo str_replace(get_blog_option($blog_id,'fileupload_url'),get_blog_option($blog_id,'upload_path'),get_post_meta($post->ID, "post-img", true)); ?>&amp;h=150&amp;w=200&amp;zc=1" alt="<?php echo (get_post_meta($post->ID, "post-img-alt", true)) ? htmlspecialchars(get_post_meta($post->ID, "post-img-alt", true)) : the_title(); ?>" class="alignright" style="width:200px; height: 150px;" />

Code Explanation

  1. First of all, we use the bloginfo(‘template_directory’) function to pull the directory in which you’ve saved the timthumb.php file. If you’ve saved timthumb.php somewhere else on your Web server, you should adjust that accordingly.
  2. Next, we echo the get_current_site(1)->path parameter, which will be the actual URL (relative to the root domain) at which your main WPMU blog is located. This will be the actual root of the path that leads to your uploads directory. As @andrea_r pointed out to me on Twitter, WPMU uses the term “site” to refer to the root of the WPMU installation, and, since it is apparently possible to install multiple “sites” within WPMU, the ID of 1 will always refer to the initial “site” you installed.
  3. I’ve then written a small snippet of code that replaces the permalink URL of your uploads directory with the actual URL to your uploads directory. To do that, I’m using the PHP str_replace function to search for the fileupload_url (which is the WPMU taxonomy for the permalink version of the uploads URL) and replace it with the upload_path (which is the WPMU taxonomy for the actual path to your uploads directory; but it’s relative to the root of the WPMU installation, which is why I added the path of the root WPMU install in the first item mentioned above). That str_replace function is searching and replacing within the “post-img” meta element we set for the post (which, if you followed the steps I outlined in the first portion of this post, should be the URL that WordPress provided you when you uploaded the file).
  4. The rest of the code can be completely customized for your needs. You can adjust the width and height of the image that TimThumb returns by adjusting the “w” and “h” parameters in the query string (if you adjust the width and height, you will need to adjust them in the style definition, too) and you can specify whether TimThumb simply resizes the image or if it partially crops it when it resizes it (recommended).
  5. I then wrote a small snippet of code that checks to see if the post-img-alt meta element is set. If it is, we use that as the alt tag for the image. If it isn’t, we use the title of the post as the alt tag.

What Can You Do With This?

Using the post-img meta element you created and the TimThumb script as I’ve shown above, you can use the same original image to dynamically show it in multiple sizes across your blog.

For instance, you could shrink it to an icon size and use it in the related posts area as shown in the Smashing Magazine article. You can size it to a thumbnail size and use it when showing a list of blog entries (for instance, on your blog’s home page). You can then resize it again to a almost full size for use within the post itself. In fact, you could even use the TimThumb script twice in your index.php template file to show a banner-sized image on the first blog post and a thumbnail-sized image on the rest of the posts; if you were to work on implementing the third suggestion in the Smashing Magazine article (a great example of a blog using that type of home page is the dotEduGuru blog).

However, before implementing any of the suggestions in the Smashing Magazine article, you should make sure to review the code (and, hopefully you have a good understanding of PHP and WordPress functions), as there are (at the time of this writing) quite a few errors in the code examples. For instance, in suggestion number three, the author says that you can show three entries at the top, but uses $postnum<=3 (which would go from 0 to 4, rather than 0 to 3) to test and see if the post should be styled differently. Also, as someone in the comments pointed out, the author failed to increment the $postnum variable within the code sample.

12 Responses

  • Initially I get a syntax error. :( Ooops!

    Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ‘,’ or ‘;’ in

    • Unfortunately, part of your comment was cut off, so it’s difficult to figure out where you might have encountered the issue.

      • Error I received is

        Parse error: syntax error, unexpected T_OBJECT_OPERATOR, expecting ‘,’ or ‘;’ in /home/socal/public_html/wp-content/themes/agent_10/home.php on line 20

        • I’m assuming that the call to TimThumb is on line 20 of your home.php theme file?

          Do you happen to know which version of PHP you’re running on your server? It just occurred to me that the way I have this written, it will only work in PHP5.

          You could try replacing echo get_current_site(1)->path; with $curSite = get_current_site(); echo $curSite->path; and see if that makes a difference.

          If that still fails, try breaking up the PHP into separate lines (start a new line after each semi-colon in the PHP code or after each opening <?php tag.

    • That worked fixed it, but now the upload path doesn’t appear.

      For example,

      http://domain.com/wp-content/themes/theme/tools/timthumb.php?src=/&h=150&w=200&zc=1

      Any thoughts?

      • Strange. Try testing the output of your script periodically by printing the output and then killing the script.

        For instance, try using the following code inside the loop in your template:
        <?php $curSite = get_current_site(1); echo $curSite->path; die(); ?>
        If that prints something, then try:
        <?php echo get_blog_option($blog_id,'fileupload_url'); die(); ?>
        If that prints something, try:
        <?php echo get_blog_option($blog_id,'upload_path'); ?>
        Finally, if all of those have printed some output, try:
        <?php echo get_post_meta($post->ID, "post-img", true); ?>

        That will help you diagnose which functions are failing or not returning anything.

  • First one echo’s /
    Second echo’s http://domain.com/files
    Third: wp-content/blogs.dir/1/files
    Last one returns the post_meta!

    BUT, I think I figured out what is stopping us. If I visit the URL that it outputs, it gives me the following error:

    =========================================

    Warning: mkdir(./cache) [function.mkdir]: Permission denied in /home/socal/public_html/wp-content/themes/agent_10/tools/timthumb.php on line 454

    Warning: chmod() [function.chmod]: No such file or directory in /home/socal/public_html/wp-content/themes/agent_10/tools/timthumb.php on line 455

    Warning: touch() [function.touch]: Unable to create file ./cache/26a900be320d8619eb23d610e2b6dfba.png because No such file or directory in /home/socal/public_html/wp-content/themes/agent_10/tools/timthumb.php on line 241

    Warning: Cannot modify header information – headers already sent by (output started at /home/socal/public_html/wp-content/themes/agent_10/tools/timthumb.php:454) in /home/socal/public_html/wp-content/themes/agent_10/tools/timthumb.php on line 251

    =========================================

    Visit the following URL to view the error. At this point I am not sure why it’s returning permission denied.

    http://searchonsocal.com/wp-content/themes/agent_10/tools/timthumb.php?src=/wp-content/blogs.dir/1/files/2009/09/wordpress_normal.jpg&h=150&w=200&zc=1

  • Figured it out, needed to set proper permissions to tools/

    I was wondering if we could rewrite this function so we can eliminate the custom field

    function sp_get_image($num = 0) {
    global $post;
    $children = get_children(array(
    ‘post_parent’ => $post->ID,
    ‘post_type’ => ‘attachment’,
    ‘post_mime_type’ => ‘image’,
    ‘orderby’ => ‘menu_order’,
    ‘order’ => ‘ASC’
    ));

    $count = 0;
    foreach ((array)$children as $key => $value) {
    $images[$count] = $value;
    $count++;
    }
    if(isset($images[$num]))
    return wp_make_link_relative(wp_get_attachment_url($images[$num]->ID));
    else
    return false;
    }

    • Eddi – I’m not sure about rewriting that function, but I do know that I’ve seen a plugin or function that supposedly automatically detects images within posts. It could probably be used to eliminate the custom field and just use whatever the first image is that’s included in the post. I’ll see if I can find it, test it and write a post about it (making sure that it works with WPMU, of course).

  • I briefly spoke with Andrea_R, she mentioned Get The Image plugin:
    http://justintadlock.com/archives/2008/05/27/get-the-image-wordpress-plugin

    I am reading through the documentation right now, figuring out how this may work. Idea’s off the top of your head?

  • Hey,

    I am having a similar kind of problem. I am trying to display this though on the homepage of my WPMU install using timthumb.php, which I have installed my homepage theme directory. I am putting all the code in the functions.php file, which I think may be causing the problem. Here is my code, any help would be great:

    function get_recent_blogposts_featured_nfl($blog_id,$show){
    wp_reset_query();
    switch_to_blog($blog_id);
    global $post;?>
    have_posts()) : $my_query->the_post();
    $do_not_duplicate = $post->ID; ?>
    <img src="/tools/timthumb.php?src=ID, “thumb”, $single = true); ?>&h=150&w=350&zc=1″ /><a href="” rel=”bookmark”>

    <?php restore_current_blog();
    }

    Thanks,
    Grant

  • Ha, wish I would have found this yesterday! I had a very similar issue when trying to display media uploaded from one MU site on a different MU site. I came up with a slightly different solution ( http://andrewroycarter.com/wordpress-2/using-timthumb-on-wordpress-multi-user/ ) but I like yours a lot! Also, timthumb rules ^_^

Post Your Comment

Your email address will not be published.