Mar 03
Generating Flickr Short URLs with JavaScript
As of this past Saturday, users who click a “tweet this” link on an individual photo in Portwiture may notice a few extra characters available. By popular request, the app now takes advantage of Flickr’s URL shortening.
What’s unique about flic.kr URLs is that they are not directly tied to a database or fetch-able via the API, but derived from a photo’s unique ID using a variation of base58 compression. This is actually pretty neat, as it sidesteps the need for an additional database query, resulting in a faster experience for the end user.
The only problem is that you, the developer, have to do the work to generate the darn thing. If you need to create it on the fly using JavaScript (as Portwiture does), you may be disappointed by the relative lack of JS code snippets in the official base58 flic.kr dev discussion.
Fear not! Using their PHP example, translating this functionality to JavaScript is a straightforward process.
The only function used therein with no direct JavaScript equivalent is intval. Luckily, the amazing php.js project has us covered with a translation. Grab that function and include it in your source.
Now we simply rewrite the base_encode function, swapping out strlen for .length, [] for .charAt(), and so on.
function base_encode(num, alphabet) {
// http://tylersticka.com/
// Based on the Flickr PHP snippet:
// http://www.flickr.com/groups/api/discuss/72157616713786392/
alphabet = alphabet || '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
var base_count = alphabet.length;
var encoded = '';
while (num >= base_count) {
var div = num/base_count;
var mod = (num-(base_count*intval(div)));
encoded = alphabet.charAt(mod) + encoded;
num = intval(div);
}
if (num) encoded = alphabet.charAt(num) + encoded;
return encoded;
}
Note that the default alphabet differs slightly from honest-to-goodness base58 encoding, omitting certain characters that are confusing in URLs (0 and O, I and l, etc.).
Assuming you’ve already fetched a Flickr photo ID, generating a short URL is now as simple as this:
var shortURL = 'http://flic.kr/p/' + base_encode(4379822687);
alert(shortURL);
// Should alert 'http://flic.kr/p/7F2JGg'
That’s all there is to it. Reversing the process is a bit trickier (you need to fetch the author’s name), but this Flickr discussion should get you started.
Want a JavaScript file with intval, base_encode, base_decode and a few helper functions ready and raring to go? You’re one lucky son of a gun:
Feb 24
How WordPress 3.0 will rock your portfolio
I couldn’t be happier that my WordCamp Portland 2009 presentation, WordPress-Powered Portfolios, will likely have the shortest shelf life of any presentation I’ve given. It’s a testament to the WordPress team (and open source projects in general) that the “hacks” I proposed only months ago have already blossomed into honest-to-goodness features.
In December, WordPress 2.9 introduced support for post thumbnails, eliminating the need for my custom meta hack. WordPress 3.0 (which should be released around May) will solve the problem of secluding portfolio content from your blog with the introduction of custom post types.
Instead of corralling your portfolio content with tools like “category excluders” or relying solely on nested pages (as I suggested), you’ll soon be able to create a custom “portfolio” post type in a supported and predictable fashion.
As Frank Bültge details on the WP Engineer blog, adding a whole new section to your WordPress sidebar will be a straightforward and extremely flexible process you can bake right into your theme. No crazy plugins or hackery required!
This change is exciting not only for the impact it will have on sites like my own, but because it increases WordPress’ prospects as a hardy CMS solution.
All that’s left to render my presentation completely obsolete is a more robust and customizable gallery solution. I’ll be crossing my fingers.
Jan 04
Ring in the new year with a little PHP
I think this has happened to every web developer at one point or another: You complete and launch a site, revel in it’s glory, January 1st passes you by and suddenly, embarrassingly, the site proudly proclaims the previous year in the footer!
Ack! How’d you miss that? So unprofessional.
Many of you have probably used the following solution to combat this troublesome oversight:
<?php echo date('Y'); ?>
In PHP, this displays the current year. But what if you want to intelligently display a span of time, regardless if your project launched this year or five years ago?
Here’s a fun little function my good friend (and ace developer) Peter Wooley showed me some time ago:
function copyrightYear($start,$between='-',$echo=true) {
$current = date('Y');
$result = $current > $start ? $start.$between.$current : $start;
if ($echo) echo $result;
return $result;
}
The first attribute ($start) is the launch date of your site, the first year of the date span. $between is what goes between the start and end year (when applicable). If you set $echo to false, the value will be returned instead of echoed.
So if your site debuted in 2009, you would use the following:
<?php copyrightYear(2009); ?>
If the year is 2009, it will echo ’2009′. In 2010, it will echo ’2009-2010′.
Now sit back and rest easy next New Year’s Day knowing your footers shan’t go out of date again!
Dec 19
Implement 2.9′s thumbnail feature in your WordPress-Powered Portfolio
WordPress 2.9 was unleashed upon the world last evening with a pile of killer features (image editing, anyone?). Perhaps my favorite new feature is built-in support for thumbnails associated with a page or post.
When I discussed building WordPress-Powered Portfolios earlier this year at WordCamp Portland, you may recall my rather obtuse solution for supporting thumbnails. Basically, you were required to upload an image, copy its filename, close the media browser, create a new custom field called “tn,” and paste the filename into it.
No longer!
With support in your theme for 2.9′s post thumbnails, simply upload an image and assign it as the thumbnail with a single click (or through the handy new “Page Image” box in the lower-right corner). No custom fields to mess with, no copying and pasting filenames.
Implementing this feature in a portfolio already using my WordCamp functions is a three-step process.
- Tell WordPress that the feature is supported by adding
add_theme_support('post-thumbnails');somewhere in your theme’s functions.php file. - Log in to WordPress and assign each of your portfolio items an image. If you’ve already used the “Upload/Insert” tool to add them prior to 2.9, just click the “Add an Image” button, then “Gallery,” “Show” the image you want to use and click the “Use as thumbnail” link toward the bottom.
- Adjust your functions to support the new feature. Refer to my updated list_work function snippet as an example.
Your mileage may vary depending on the volume of portfolio items you’ll need to switch over, but it took me roughly an hour to support the feature on this very site.
I recommend reading Justin Tadlock’s excellent blog post on the subject, which details the post thumbnails in much greater detail than WordPress’ documentation and was of great help to me in supporting them.
I do have one bit of extra theme development knowledge to bestow on other developers which I was unable to find elsewhere online. To echo only the URL of the thumbnail image file, use the following:
<?php echo get_post(get_post_thumbnail_id())->guid; ?>
Sep 30
WordPress-Powered Portfolios: The Movie
If you didn’t grab a ticket to WordCamp in time, missed the live stream and/or found my presentation slides seriously lacking in the audio department, you’re in luck! The video of WordPress-Powered Portfolios has been published to WordPress.tv, or you can watch it below.
A technical problem resulted in the footage starting a few minutes into my presentation. All you missed was an introduction of who I am, and of my background as a cartoonist.
I apologize for having to look down at my notes so often; I didn’t expect to be holding the microphone! Other than that, enjoy.
Sep 19
WordPress-Powered Portfolios: Slides & Snippets
I really dig WordPress, but not nearly as much as I enjoy spending time with my fellow geeks and colleagues in Portland’s bustling and vibrant open source and web community. It was a pleasure presenting this afternoon!
My presentation was meant to solve the problem of simply and easily associating imagery with pages and/or posts in order to build a killer portfolio theme. I hope designers, artists and hobbyists will use these tips as a springboard for pushing what we can do with this constantly-evolving platform.
Thanks to all in attendance! Here are the goods.
Sep 16
WordPress-Powered Portfolios this Saturday
Wow, time flies! I last wrote about WordCamp Portland back in June, and already the event is upon us. This coming Saturday, I’ll be closing the first day of the sold-out shindig at WebTrends with my presentation, WordPress-Powered Portfolios. (Don’t panic, they’re streaming it.)
My presentation won’t revolve around the visual design of portfolio sites for two important reasons:
- The principals of compelling interaction design are not exclusive to the WordPress platform.
- I’m still way too new at this to represent myself as any sort of authority on the art of portfolio design.
What you will learn is whether or not WordPress is the right platform for your online presence and, if so, the surprisingly simple snippets of PHP you’ll need to get there.
As excited as I am to present, I’m even more excited to see the other wonderful speakers, including WordPress founder Matt Mullenweg.
I was surprised and delighted to hear that the premier sponsor of the event is Microsoft. I acknowledge their generous support by drafting and publishing this post in their intuitive Windows Live Writer application.
See? WordPress brings people together.
Jan 28
Smarter WordPress Comment Status
I love WordPress more and more with each release, and 2.7 takes the cake; I’ve never been a happier designer, developer or user of a CMS/blogging platform. As awesome as it is 95% of the time, I did encounter a setback when developing this site’s theme, specifically in the behavior of comment links.
One of the goals of my site redesign was to open up opportunities for conversation, and journal comments are a significant part of that. As such, I wanted the links to the left of the journal items to behave in the following way:
- If comments are open, always display a link to them or to the comment form.
- If comments are closed, but the post has comments (presumably made before the closure), display the link.
- If comments are closed, and the post has no comments, there isn’t any reason to maintain the link; don’t show it at all.
I wanted to customize the style and destination of the comment link a bit more than the usual comments_popup_link function would allow. I took some cues from the default theme and referenced $post->comment_status, resulting in the following conditional:
if (get_comments_number() || 'open' == $post->comment_status) {
Comment stuff...
}
Unfortunately, this had one flaw; any posts where the comments were closed as a result of WordPress’ “automatically close comments after x number of days” setting retained the comments link no matter what. While $post->comment_status appeared to work correctly in comments.php, elsewhere it would still return 'open' for those posts which had not been implicitly closed.
My solution was to create a function in my theme’s functions.php file called showCommentLink, which checks the number of comments, post status and the automatic closure preference before returning a boolean (true for show, false for hide). Take a look:
function showCommentsLink($num,$status,$date) {
// If number of comments is zero, check some other stuff
if ($num <= 0) {
// If comment status is not open, return false
if ($status != 'open') {
return false;
}
// If comment status is open, check if automatic closure is enabled
$close = get_option('close_comments_for_old_posts');
// If so, grab the number of days and compare
if ($close) {
$days = get_option('close_comments_days_old');
$cutoff = strtotime("-$days days");
$then = strtotime($date);
// If this post's comment status is "expired," return false
if ($then < $cutoff) {
return false;
}
}
}
// If you've made it this far, return true
return true;
}
And sample usage in The Loop:
if (showCommentsLink(get_comments_number(),$post->comment_status,$post->post_date)) {
Comment stuff...
}
While definitely not the prettiest solution in the world, it appears to do the trick. Having $post->comment_status behave differently in different contexts seems like either an oversight on the part of WordPress developers or, potentially more likely, a sign that I am doing something a bit backwards.
What’s your take? See something I’m doing wrong or have a way to improve the function? Want to see me port it to a plugin for more streamlined use in The Loop? Think all this WordPress stuff is a waste of time when I could use Drupal instead? Let me know in the comments!