WordPress Tip: Careful with that Autosave, Eugene

Published Monday, March 17, 2008 @ 9:41 am • 10 Responses

After upgrading WordPress from version 2.0.5 to 2.3.3, I did some experimenting with the “post autosave” feature. The autosave feature uses some crafty ajax to automagically save your post every 2 minutes (120 seconds by default). Below the post-editing field, you will notice a line of text that displays the time of the most recent autosave, similar to the following:

[ Screenshot: WordPress Autosave Message (Saved at 2:34:02.) ]

Surely, this relatively new feature provides an added layer of protection against lost work, but all is not perfect (yet) in the world of automatically saved content.

Several months ago, I lost several hours of work because the autosave feature completely failed to work, despite the periodically reassuring “Saved at..” message. After working for several hours with a false sense of security, WordPress choked and my post had vanished. In shock, I scoured the database for any trace of my recent efforts, but to no avail. The entire post had disappeared into the void. Utterly devastated and disillusioned, I decided to investigate the so-called “autosave” feature, learn what had happened, and take steps to avoid such travesty in the future. Here is a summary of my investigation..

A few notes on the WordPress Autosave feature

The reason autosave failed — Although autosave seemed to be working as expected, all data was lost after I had clicked the “Save” button and received an unexpected server error. Apparently, either my server or WordPress (or both?) doesn’t respond well to various types of character combinations (e.g., the term “.htaccess”), and will utterly reject any post input containing such “invalid” content.

So, without realizing that I had included some forbidden character string, I habitually hit the save button, only to trigger an error and get redirected to a server-error page. Oops, but not a big deal, right? After all, “WordPress Autosave has my back.” Or so I thought. Upon returning to the admin screen, I found no trace of my post. A thorough examination of the database confirmed that autosave had saved absolutely nothing: I lost three-plus hours of diligent work — poof! — just like that.

Moral of the drama: Don’t rely on WordPress Autosave if the possibility exists that your content will trigger an error when saving or publishing your post. I can’t say that autosave will always fail in such cases, but I can say that it is definitely possible. Moving on..

How do you know if autosave actually worked? — If autosave managed to do its job and save your post content, WordPress will display a link to a draft of your saved post. I have seen this link in either of two places, depending on your user status:

  • as an individual link located above the post-editing panel, or
  • mixed in with other posts listed within the post management panel

If you think that you may have lost some content, and don’t see a draft version of your autosaved post in either of these locations, an autosave failure is highly probable. You may have better luck than I did, however, by searching through your associated WordPress database for the missing content. If you did lose work, believe me, I feel your pain.

Implement a backup strategy — As nice as the concept of “autosave” sounds, don’t rely on it to save your work. Think of it as an added layer of protection against boo-boos, but treat it as nothing more than a bonus feature that may or may not work as intended. Seriously, losing three hours of meticulously crafted material is a total drag. Since then, I have adopted a new strategy for backing up my posts while working on them:

  1. Work for few minutes or type a few paragraphs
  2. Ctrl-A, Ctrl-C, Ctrl-V into a blank .txt file
  3. Work for few minutes or type a few paragraphs
  4. Ctrl-A, Ctrl-C, Ctrl-V to replace previous .txt copy
  5. Wash, rinse, repeat..

I have been doing this for several months now, and the practice has become almost second-nature. It takes only a few extra keystrokes and a few microseconds, but the habit has already saved my rear on several occasions. Then, as an added bonus, when I am finished writing the post, I also copy & paste the date, title, keywords, description, excerpt, and tags to the text file, save it as the name and date, and zip the monthly collection of posts into a nice archive directory. Paranoid and tedious? Perhaps. Time-saving and reassuring? Definitely.

How to change the time-interval for the WordPress Autosave feature

While experimenting with the autosave feature for this post, I discovered how easy it is to change the default autosave time interval. In WordPress 2.3 (and probably 2.2 and 2.1), open the wp-includes/script-loader.php and edit the instance of 120 (seconds) to something more appropriate. Don’t get too crazy though, or you might get a nasty email from your host. Here is how the interval-setting code appears on line #43:

'autosaveInterval' => apply_filters('autosave_interval', '120'),

Other stupid Autosave tricks..

While tinkering, I also learned that it is just as easy to customize the default messages displayed throughout the autosave process. While saving your draft, WordPress displays the text, “Saving Draft…”. Then, in between saves, the text “Saved at 2:34:02”, as displayed in the previous screenshot. To change either of these default messages, open the same file as before (wp-includes/script-loader.php), and edit the following lines to suit your needs:

// line #45 >>
'saveText' => __('Saved at %time%.'),

// line #47 >>
'savingText' => __('Saving Draft...')

Other interesting autosave quirks

Also during the investigation, I happened to stumble upon an interesting discovery concerning a common technique for displaying a blog’s annual archives. WordPress provides the following built-in methods of querying and displaying daily and monthly archive listings:

<?php wp_get_archives('type=postbypost'); ?>

<?php wp_get_archives('type=monthly&show_post_count=1'); ?>

However, earlier versions of WordPress did not provide similar functionality for the presentation of yearly archives. To accommodate this missing feature, many WordPress users and theme developers have employed the following, highly prevalent method:

<ul id="archives">
	<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts ORDER BY post_date DESC"); foreach($years as $year) : ?>
		<li><a href="<?php echo get_year_link($year); ?>"><?php echo $year; ?></a></li>
	<?php endforeach; ?>
</ul>

Fair enough, that trick definitely does the job, however, drafts and autosaved posts produce some unexpected results. Specifically, post drafts are stored along with published posts in the wp_posts database table. Thus, the above query returns a “year” for all post drafts and displays their values in the annual archive list. Any post draft that happens to be a working “autosave” draft will return a zero (i.e., “0”) for the above yearly archive query (see screenshot). In other words, drafts are saved with a post_date of zero. Also, any posts that are deliberately saved as “draft” (i.e, any post that is not published) will also display a zero if the previous database query is used. Fortunately, there are at least THREE easy ways to prevent meaningless zeros from populating your annual archive list:

1. Re-save the draft(s) with an explicit time stamp (hint: pick a year that already exists in the annual archives).
2. For users of WP versions less than 2.3, tweak the database query to ignore posts with “draft” status:

<ul id="archives">
	<?php $years = $wpdb->get_col("SELECT DISTINCT YEAR(post_date) FROM $wpdb->posts WHERE post_status = 'publish' ORDER BY post_date DESC"); foreach($years as $year) : ?>
		<li><a href="<?php echo get_year_link($year); ?> "><?php echo $year; ?></a></li>
	<?php endforeach; ?>
</ul>

3. Even better, for WordPress 2.3 and beyond, simply replace the direct database call with the new “built-in” hotness:

<ul>
	<?php wp_get_archives('type=yearly&show_post_count=1'); ?>
</ul>

This third method includes several useful parameters, including the ability to display the post count next to each year.

Wrap up..

That’s it for this post! See you next time with another fun-filled and educational adventure into WordPress land!


Dialogue

10 Responses Jump to comment form

1Frank

March 18, 2008 at 3:39 am

at version 2.5 at WP is the autodraft-function new and the time-interval is 60s in standard.
You can define a konstant in wp-config.php for other times, maybe 1s.
define( 'AUTOSAVE_INTERVAL', 1 ); // Autosave interval

I hope and wish, the function is realy better in 2.5.
best regards

2teddY

March 18, 2008 at 7:38 am

Wow this post definitely packs a big punch :) thanks for highlighting the autosave failure issue, I get that quite often as well. My drafts fail to save properly so much so that I resort to copying the raw HTML code and pasting it in a text edior every few minutes and before I publish for the post. I can partially blame my ISP for the unstable connection (sometimes the publishing process just go timeout and the whole post is a gone-case).

I’ve been trying to edit the autosave intervals among the wordpress files, thanks for telling me where it is :D

Oh and when I logged in to Wordpress today, they say 2.5 beta is out! The dashboard looks so different, I’m very impressed. I hope they don’t change the autosave script since what you’ve provided is a great fix!

3H5N1

March 18, 2008 at 8:02 am

…or one of these days I’m gonna cut you into little pieces :)

4Perishable

March 18, 2008 at 9:40 am

@Frank: Thanks for the information. I am looking forward to working with WordPress 2.5. I assume the define() interval is in minutes?

@teddY: Very wise to copy/paste your post content every few minutes, and especially right before hitting the “Publish” button! I also copy any custom fields into the text file, including tags, meta information, and the title. From what Frank says, it sounds as if customizing the autosave interval is much easier in WP 2.5. In any case, it looks like I posted this information just in time — hopefully it will still help users of previous versions of WP! ;)

@H5N1: Exactly :)

5teddY

March 18, 2008 at 10:17 am

That’s the idiot-proof way of not losing my precious posts, heh. Oh, and yea sometimes weird things happen when you save or republish a post - the tags just disappear for no reason! I’ve got it a few times, and now I’m forcing myself to either take a mental note of the tags or copy them wholesale into notepad :)

Idiot-proof workarounds are always the simplest, but hey what you’ve provided saves a lot of trouble from all the copy and pasting.

P.S. that’s a very quick reply from you!

6Frank

March 18, 2008 at 10:55 am

maybe, i think is in seconds, when i tested with 1, then saved evry 1s an edit-area.

7Perishable

March 19, 2008 at 10:29 am

Yes, that makes sense.. The autosave function uses an interval defined in seconds for WordPress 2.3 as well. Seconds are better because they enable a greater specificity for the interval. Thanks for the info!

8Lockblog

June 24, 2008 at 12:12 pm

It never even occurred to me that the auto-save wouldn’t actually work. I very often do the Ctrl-A, Ctrl-C ting, and, in fact, just a few minutes ago, I nearly did it. But no… Instead I glanced at the “Saved at…” line and thought, “It’s ok, it has saved it”!

Wrong!

Didn’t anyone tell the WordPress developers that you do a proper read-back of the database?!?!

9Perishable

June 24, 2008 at 1:18 pm

Apparently not, unfortunately, although some sort of a plugin to enhance the WordPress autosave feature would surely be worth the effort. Just think of all the lost work and time that would be saved with some reliable autosave functionality. Could save into the database as well as to a text file, provide configuration options, time intervals, custom settings — the whole bit! Now, if I could only find the time.. ;)

Subscribe to comments on this post


Share your thoughts..

TopRead official comment policy

← Previous post • Next post →

« XHMTL/CSS Remix: Creative Commons LicenseCustom HTTP Errors via htaccess »

Contact Perishable Press

  • Contact Jeff via form

Search Perishable Press

About Perishable Press

Perishable Press is the virtual playground of Jeff Starr — visionary, founder and lead developer of Monzilla Media, a small web and graphic design company in the lush desert oasis of Moses Lake, Washington. Perishable Press features articles and tutorials on many aspects of digital design..

Read more..

Perishable on Twitter

mmmm, dark chocolate..

Perishable on Tumblr

Tons of Firewalls

Tuesday, 7 October 2008, 1:45 am

Recently overheard on conservative talk radio (instructing listeners how to obtain a free promotional video from their new website):

“This website has tons and tons of firewalls, so you have to use your real email address to download the video..”

The Quiet Search Revolution

Monday, 6 October 2008, 12:15 pm

Just a thought.. As awesome as Google is these days, it would suck if they ended up owning the entire search-engine business. When they get to the point where all competition is impossible (due to their sheer size, financial resources, media influence, etc.), how many alternate search engines will have the resources for continuous improvement and top-quality search results? When this happens, we will have no choice but to do exactly what Google tells us to do.

As deeply ingrained as it is for everyone to instinctively and unthinkingly turn to Google for their search activity, it is time to leave a few alternate search tabs open for as much use as possible. Instead of using Google just because that’s what you always do, try your search on MSN, Yahoo, Ask, or any of the other independent search engines instead. Sharing traffic with other search engines is a nice, quiet way to keep the competitive spirit alive and well in the search-engine business.

Disappearing WordPress Posts

Wednesday, 1 October 2008, 7:50 pm

Today I experienced difficulties while trying to publish or even save new posts in WordPress. I would compose the post as usual, add all of the keywords, tags, meta tags, and so on, but as soon as I clicked the “Publish” or “Save” button, the post would just disappear from existence.

The weird thing is that during the drafting process, WordPress’ default auto-save feature showed that the post had been saved at expected intervals. Unfortunately, after trying to publish several different posts, WordPress showed absolutely no record of the posts ever being created. They simply vanished into thin air.

Fortunately, a little investigation revealed the culprit. If you should find yourself dealing with this same issue, here are some different things that you should try. First, re-upload fresh copies of your entire WordPress installation. I don’t know why exactly, but apparently various files can either go stale or completely disappear from the server. Overwriting or writing fresh files may do the trick.

If that doesn’t work, check your WordPress database for errors. In my case, a little investigation revealed that something had caused a couple of fatal errors in the wp_posts table. Fortunately, checking and repairing the table solved the issue.

Tumblr Battles

Wednesday, 1 October 2008, 5:30 pm

Please excuse the duplicate Tumbr posts.. seems there is no way to ping Tumblr to refresh/rebuild the RSS feed according to changes in post content. So, to resolve the issue I have discussed now like two or three times regarding paragraph elements and proper feed formatting, I have no choice but to repost a majority of my text posts.

This is necessary for the proper import and display of my Tumblr feed into WordPress. Currently, there are five items displayed at once, each styled according to proper inclusion of paragraph tags. Thus, whenever the Tumblr feed “forgets” to enclose single-paragraph posts with the proper tags, the result is an unstyled post entry displayed on my site.

Assuming that makes sense, you will please excuse my dust while I repost a few older entries in an attempt to reconstruct (the hard way) a properly formatted Tumblr feed.

More Optimization Measures

Wednesday, 1 October 2008, 5:27 pm

Another important step in improving the performance of my recent redesign involves the optimization of both CSS and JavaScript content. During development there were around 15 server requests for these two types of files, 10 JavaScript files and 5 CSS files. This was okay for my own use, but would not work for production purposes.

Optimizing these file types involves consolidation, compression, and caching. Consolidation of 10 JavaScript files into three is huge improvement. Now I deliver one JS file for the functionality of the site, one for Mint, and another for Analytics. Likewise for the stylesheets; after consolidation, a single stylesheet is delivered to all modern browsers. There are two additional stylesheets as well, but they are targeted at IE6 and mobile browsers and will not load elsewhere.

Once the files were consolidated as much as possible, it was time to optimize or “crunch” them. Using the sexy Flumpcakes CSS optimizer, I was able to reduce my stylesheets by around 25%. Likewise for JavaScript, I used xtreeme.com’s optimizer to shave an additional 20% off the size of my JS content.

Finally, once I had consolidated and compressed my JS and CSS files as much as possible, I wanted to further my optimization efforts by ensuring that these files were cached by the browser. By setting far-future Expires headers for everything but the statistical files, my site gains an additional performance boost by eliminating the need to reload preexisting content.

Read more on Tumblr..

Subscribe to Comments Recent Dialogue

  • Nyx: Happy to have helped! Love your site....
  • dockside: Hi i want to use this code on my blog. but not for all post. I want 3 or 4 full posts and then post in double column How?...
  • NZ Beats: Got it working using the following: http://www.nzbeats.com/?feed=rss2&category_name=album-review...
  • Paul: Holy crap, you just saved my A$$! Thank you!...
  • free games: Google have a content distribution network here http://code.google.com/apis/ajaxlibs/documentation/#AjaxLibraries where you ca...
  • free games: Found this (untested) for those that just want https For HTTPS: var pageTracker = _gat._getTracker("UA-XXXX-1"); pageTracker...
  • H5N1: The question is very hard. No way to solve it in only few words :) First of all you need a Linux. OK. But Linux it's only a Kerne...
  • gowers: wow, your theme is so great, I like it...
  • Eric Ferraiuolo: Like some people are commenting, a virtual solution is going to be the easiest to get going with the least number of issues. I would ...
  • Brent Terrazas: Thanks for the mention, I currently am running Ubuntu Server 8.04 on VMWare Fusion beta (it's a free beta download.. check it out fo...

Read more recent comments..