Tutorials WordPress

Add a Twitter-like “Published X Days Ago” timestamp to your WordPress posts

For the last couple of weeks I’ve been working on a massive WordPress project that has required a lot of interesting and unusual components that step well outsie of what is normally expected from WordPress and its plugins. Once the project is live I’ll write a longer article about all these components, but in the meantime I’m going to share some of the functions because I think you might find them useful.

“Published X Days Ago”

The first function I’ll feature is a small script that spits out a text telling the viewer how long ago a post was posted. I actually needed this script for a countdown so mine is a fair bit longer, but it can be used to create a Twitter-like time stamp just as easily.

To achieve this we’ll be using two functions, date() and get_the_time(). The former is a bona fide PHP function that grabs the current local time from the server while the latter is a WordPress function that grabs the time of publishing for the post.

It doesn’t take a genius to figure out how we’re going to use these two: Taking the current time and subtracting the published time will give you the time difference, in other words how long ago the post was published. The challenge is that you need to get the right time formats to actually output a rational result.

Getting the right kind of time

You’d think that if you want to count how many days ago a post was posted you could just grab the dates and count backwards. But that’s actually pretty hard because it relies on the counting mechanism knowing what day of the month it is and how many days each month has etc etc. A better solution is to grab a unified time value that doesn’t change in the same arbitrary way. Luckily programmers found this problem and its solution a long long time ago. It is called the the Unix Epoch and is the time, in seconds, since January 1, 1970 00:00:00 GMT). To get this value for each of our functions we simply add in the format string “U” like this:

date('U'); // outputs the current date and time in Unix Epoch terms
get_the_time('U'); // outputs the publishing date and time in Unix Epoch terms

Making the time make sense

Problem is this produces a weird long number like 6250458. This is the number of seconds since the article was published. We want the number of days, so we need to do some math.

If you have seconds and you want to make days you first have to divide them by 60 to make minutes, then divide it by 60 again to make hours and then finally divide it by 24 to make days. For 86399 out of every 86400 seconds of the day this will produce an integer (number with a comma) but we want whole numbers. So we utilize an extra function called round() that rounds out the number for us.

Putting it together

With that we have all the components we need to get the number of days since published. In PHP form the function looks like this:

	$days = round((date('U') - get_the_time('U')) / (60*60*24)); 
	echo "Published " . $days . " days ago";

This will output the number of days since published sandwhiched between the words “Published” and “days ago”. But what about the first day, when the number is zero, or the second day when the number is one? “Published 0 days ago” and “Publised 1 days ago” looks kind of sloppy, no? Well, it’s easy to fix with some conditional statements:

	$days = round((date('U') - get_the_time('U')) / (60*60*24));
	if ($days==0) {
		echo "Published today"; 
	elseif ($days==1) {
		echo "Published yesterday"; 
	else {
		echo "Published" . $days . " days ago";

All these conditional statements do is ask “if the number of days is 0, say “Published today”, if the nuber is 1, say “Published yesterda” and for all other cases say “Published X days ago”.

Copy this piece of code anywhere in your theme files within the WordPress Loop and it’ll spit out a published x days ago timestamp on your posts.

Easy as Pi.

Tutorials Video Tutorials WordPress as CMS WordPress Themes

Using WordPress in Alternate Configurations – My WordCamp Whistler 09 Presentation

Finally, after a full week of catching up, here is the video tutorial version of my presentation at WordCamp Whistler 09 for those who were there and those who couldn’t come. The video is also available on if you’d rather watch it there. I recorded the video over the weekend and it contains the entire presentation including all my fancy slides as well as the code examples and demos. The only thing you won’t see is me waving my hands around and messing up the code like I did at the actual event ;o)

Code Snippets

The last half of the presentation centers around creating Custom Page Templates and Custom Fields for layout purposes. To help you along in your own WordPress site development, here are those code snippets ready to be cut and pasted into your templates:

Custom Page Templates in 5 lines of code

This block of code is inserted at the very top of the Custom Page Template file. To get started, simply open the page.php file, save it under a different name, paste these 5 lines of code at the top of the document, save and upload to your server. To activate the new Custom Page Template just select it from the Template menu under Attributes in the Page Editor within WordPress.


Custom Fields in one line of code

This code can be used in any template file including but not limited to page.php, any Custom Page Templates, index.php, archives.php, single.php etc etc. The code returns a string of text that matches the text inserted in the custom field. Remember to replace $key with the actual name of the custom field. You can read more about Custom Fields and how to use them in the WordPress Codex.

 ID, '$key', true); ?> 

Custom Field that parses PHP code

This code is used to parse (interpret) PHP code inserted into custom fields. It is a bit wonky – for instance it terminates any other custom field code placed directly after it in a page – so use it with caution. Otherwise it works exactly as the code above.

ID, 'centerBox', true); ?> 
'.$boxContent); ?> 

Applications Used in the Presentation

After the presentation several people came up to me and asked what applications I used, so here is a short list:

BitNami WordPress Stack

The demo site I used in the presentation was actually installed and running locally within Windows 7. To achieve this I used an ingenious application named BitNami WordPress Stack. Once installed this application will run a fully functional version of WordPress with database entry, plug-ins, custom themes and everything else you want to throw at it right inside Windows (XP, Vista and Windows 7 supported) so you don’t have to keep uploading your files to a server or hassle through complicated XAMP installs to play around with WordPress while offline. You can even install several different WordPress and other open source CMS stacks on your computer simultaneously to further increase your productivity. I have no idea exactly how it works but BitNami works incredibly well. Just remember to set the IP address to “localhost” when you install it.
You can download the BitNami WordPress Stack here. For Mac users there is a similar application called MAMP but I know nothing about it.

Web Developer Add-On for FireFox

FireFox is my absolute favourite browser and I use it for browsing as well as in the design process. One of the main advantages of FireFox is the myriad of add-ons you can install that make web site development a lot easier. The one I use the most is the Web Developer Add-On. This small application within an application lets you see and mess with CSS, turn styles and JavaScript on and off and do tons of other stuff that makes it easier to dissect and troubleshoot buggy web pages. Combine it with the HTML Validator add-on and you have a true powerhouse in a small browser window.

Microsoft Expression Web 2

My web development platform of choice is Microsoft Expression Web 2. This new offering from Microsoft is what enables me to build custom WordPress themes and web sites like from scratch in less than 24 hours. There are many great things you can talk about with Expression Web 2 but for WordPress theme development the two main features is full PHP support, unrivaled CSS integration and Standards Based CSS generation right out of the box. If you want to know more about Expression Web 2 or want to learn how to use it you can read more on this blog or pick up a copy of my book Sams Teach Yourself Microsoft Expression Web 2 in 24 Hours. It’s a good read, I promise.

Expression Web

Expression Web 2 Beta Bug Report

I’ve been working with Expression Web 2 Beta for two weeks now and I’ve found it to be a vast improvement from the first release. I’ll get back to that in a later post but right now I want to share with you some interesting and annoying bugs that have gotten in the way of my work.

File tree updates and image file recognition

I don’t know why, but it seems Expression Web works with some form of paging file or log that keeps track of the files in your site. That’s all fine and dandy except it doesn’t correspond with the folder you are working in. Let me explain: When I design sites I regularly ad new folders and files outside of the program by simply copying and pasting them in explorer view. Unfortunately these changes are not reflected in Expression Web unless you hit F5 or click “Refresh”. And even then, whether the tree gets updated or not seems rather random. Especially if it’s a sub-folder you currently have exploded in the tree view. Every time I ad a new file or folder within a sub folder of the site, I have to unexplode the tree to see the update. And that’s a couple of extra mouse clicks I could do without.

But that’s just the half of it. For some reason the program has serious trouble recognizing simple image files. This problem is heavily debated in the Expression Web forum and I’ve encountered it several times. Basically if you ad an image file into an existing folder outside of Expression Web, it’s hit and miss whether that file will actually be recognized by the program. Chances are all you get is a little red X instead of the image. The only way to remedy this issue is to go to File -> Import Image and import it into the program. This seems highly unneccessary as these are standard issue files (jpg, png, gif etc) that don’t require special rendering of any sort. And it gets really annoying when you are making minute changes to an image file to make it fit your layout because every time you overwrite your old file, you have to re-import it to see that update.

To be fair, I’m not sure this last issue is a real bug or if it’s an intended feature from the Dev team. Ideally I’d like to see both of the above issues resolved so that the updating/importing of new files are done automatically. If not, my secondary option would be that both full file-tree updates and image importing is included in the F5 Update function.

The PHP destroyer

Expression Web 2 Beta does have extensive support for PHP, but it’s not quite there yet. I’ve been designing some new WordPress themes with the software and I’ve come across something really weird: On the second upload of the same file, the PHP is garbled (at least parts of it). Here’s exactly what happens:

I have a file called header.php. Right at the top of the <head> there is this line of code:

<title><?php bloginfo(‘name’); if ( is_404() ) : _e(‘ » ‘, ‘box’); _e(‘Not Found’, ‘box’); elseif ( is_home() ) : _e(‘ » ‘, ‘box’); bloginfo(‘description’); else : wp_title(); endif; ?></title>

After editing and saving the php file, I uploaded it to the server and ran a test. Everything was fine but there were some minor issues further down in the file that needed tweaking. I made the necessary changes, saved and re-uploaded the file. This time, once it reached the server, the line above read like this:

<title>&lt;?php bloginfo(&#39;name&#39;); if ( is_404() ) : _e(&#39; » &#39;, &#39;sandbox&#39;); _e(&#39;Not Found&#39;, &#39;sandbox&#39;); elseif ( is_home() ) : _e(&#39; » &#39;, &#39;sandbox&#39;); bloginfo(&#39;description&#39;); else : wp_title(); endif; ?&gt;</title>

It’s pretty evident what happened here but why it happened is beyond me and I think it’s pretty clear why I find this “mildly” frustrating. It does look a lot like the old PHP problem EW had, but what’s new is that it only appears to effect small parts of the file rather than the whole. There is plenty of PHP code further down in the same file that remains unaffected even though the <title> tag is completely garbled. Ghost in the Shell anyone?