How to Handle Post Revisions in WordPress

Post revisions in WordPress are a great idea in principle, but I can’t stand them and the fact you can’t disable or change the save interval via the Settings page is a real oversight. Not only do they take up unnecessary space in the database they also slow down your site because of it. How many times have you spent a fair amount of time editing a new post because of a spelling error or changing a sentence?

If you’re like me, more than a few.

Having revisions save every single time you you do something may not be your cup of tea so here are a couple of things you can do to change their behavior or disable them altogether.

Disable WordPress Post Revisions

Add this line to your wp-config.php file, located in the WordPress root directory, to disable revisions.

define('WP_POST_REVISIONS', false );

Limit WordPress Post Revision Count

If you just prefer to just limit how many revisions WordPress maintains add the following to your wp-config.php file, located in the WordPress root directory. Just change the value to the number you want to maintain.

 define('WP_POST_REVISIONS', 10 ); 

Delete Existing WordPress Post Revisions

To delete any past revisions you will need to delete those directly from the database. To do this you will need to access your database via phpMyAdmin or a SQL Editor and running the following query.

DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id)
WHERE a.post_type = 'revision';

Hopefully in a future version of WordPress these options will get added to the Settings to make them easier to deal with.

Schedule Random Post Time


I’ll admit, I’m about as lazy a blogger as they come and when it comes to scheduling posts to be published in the future I really despise having to decide on what day and at what time the post should appear. After hacking a few other scripts to do something very similar I ran across a plugin called Date/Time Now Button created by someone named radiok. After checking it out I found it was pretty close to what I wanted but didn’t perform a random set. Since radiok already had the javascript worked out I just “adapted” that code to work the way I wanted it to.

Schedule Random Post Time adds a button to the post, page and comments that allows you to generate a random publish date. This plugin is useful for us lazy people that would rather not take the time trying to decide what date and time in the future to schedule a post for. Simply click the button and let it decide for you. It’s pretty simple really. Simply set the maximum number of hours into the future you want posts scheduled for in the settings, then just click the button and a random date between current time and your future time will be generated for you. Easy Peasy.

Installation is simple:

  1. Download the plugin from WordPress.org.
  2. Copy it to the wp-content/plugins directory of your blog.
  3. Enable the plugin in your admin panel.
  4. Set the maximum number of hours into the future you want posts scheduled for.
  5. An option for Schedule Random Post Time will appear under Settings.
  6. Enter the verification code for each service you wish to use

Support
If you like this plugin and want to support me, leave a comment or check out my donations and support page!

Webmaster Tools Verification

All three of the major search engines offer some kind of website service. The most popular being Google Webmaster Tools. Yahoo offers Site Explorer and Bing has Webmaster Center. All three require that you verify your site and offer various methods to do so. This plugin uses the meta option and inserts a meta tag in your sites section of your site.

If you’ve used WordPress.com then this will look familiar since it’s based on that tool.

Installation is simple:

  1. Download the plugin from WordPress.org.
  2. Copy it to the wp-content/plugins directory of your blog.
  3. Enable the plugin in your admin panel.
  4. An option for Webmaster Tools Verification will appear under Settings.
  5. Enter the verification code for each service you wish to use

FAQ

  • Where do I get the verification code?
    Go to either Google Webmaster Tools, Yahoo Site Explorer, or Bing Webmaster Center, find the option to add/verify a new site then select the meta option. You be provided with a piece of code and instructions to add it to your site.
  • What do I do with the code once I have it?
    All you need is the actual content= code, the plugin will automatically format the meta tag when it inserts it.
    Ex.: Google will give you a piece of code like this: <meta name='google-site-verification' content='dBw5CvburAxi537Rp9qi5uG2174Vb6JwHwIRwPSLIK8'>
    You want to copy the code: dBw5CvburAxi537Rp9qi5uG2174Vb6JwHwIRwPSLIK8 and paste it in the input box for Google.
  • I’m using WPMU but I don’t want the plugin automatically activated for each site. Can I just put it in the wp-content/plugins directory so each blog owner can choose whether or not they want it activated?
    WPMU is no longer supported but the plugin should work fine with WordPress in network mode.

Support
If you like this plugin and want to support me, leave a comment or check out my donations and support page!

How To Add An Uninstaller To Your Plugin

On of the most annoying things I find about WordPress Plugins is that once you decide you no longer want to use one, simply deactivating the plugin, in most cases, still leaves behind a bunch of garbage in your database. Maybe you like to test a plugin to see what it does or maybe it sounded great but in reality it wasn’t quite what you were after. So you deactivate it and/or delete it thinking it’s gone right? Usually not. You might be left with altered database tables, indexes which now make your database inefficient, various settings and options that are now orphaned.

I recently decided I didn’t want to be part of this crowd. I wanted to give a reasonable option to my plugin users to 100% completely uninstall a plugin if they so chose. After a little research and some tweaking here’s what I came up with. It’s really rather simple.

There are 3 parts.
1. The uninstall form
2. The check for the uninstall submission
3. The uninstall itself

So here we go. First you need to create an uninstall form in your plugin. As you can see in the picture, I include a check box the user must check to confirm they want to uninstall the plugin. The form should look something like:

<form method="post">
<input id="plugin" name="plugin" type="hidden" value="plugin/plugin.php" />

	if ( isset( $_POST['uninstall'] ) && ! isset( $_POST['uninstall_confirm'] ) ) {

You must check the confirm box before continuing.

	}

The options for this plugin are not removed on deactivation to ensure that no data is lost unintentionally.

If you wish to remove all plugin information for your database be sure to run this uninstall utility first.

<input name="uninstall_confirm" type="checkbox" value="1" />Please confirm before proceeding

<input class="button-secondary" name="uninstall" type="submit" value="Uninstall" />
</form>

I like to wrap this in a function called pluginname_form_uninstall() to prevent conflicts then add that to the plugin options screen. Next we need to check to see if the form was submitted.

if ( isset( $_POST['uninstall'], $_POST['uninstall_confirm'] ) ) {
	pluginname_uninstall();
}

Somewhere near the top of the plugin or before execution starts add a check of the $_POST vars to see if our uninstall option was submitted. If it was we call the third piece of this puzzle, the uninstall function itself.

function pluginname_uninstall() {

	delete_option( 'plugin_version' );
	delete_option( 'plugin_options' );

        // This is where you would remove and tables, indexes or fields you added when your plugin was first activated. Also anything else that caused modification to the database should be undone here.

        // Do not change (this deactivates the plugin)
	$current = get_settings('active_plugins');
	array_splice($current, array_search( $_POST['plugin'], $current), 1 ); // Array-function!
	update_option('active_plugins', $current);
	header('Location: plugins.php?deactivate=true');
}

This is pretty simple but it depends on what you’ve added to the database.

  • First use the delete_option function to remove any settings added to the wp_options table.
  • Next undo any SQL modification you made when your plugin was created. Any tables, fields or indexes added need to be removed or changed like your plugin was never there.
  • The final part deactivates the plugin and switches the user to the plugins management screen.

At this point the plugin can be activated again or deleted.

As you can this this really is fairly simple, I’m not why more developers don’t use something similar to this. I for one can’t stand to have a cluttered up database of things I don’t need.

WordPress 3.1 Finally Adds Long Awaited Admin Bar


I just got finished updating my blogs to WordPress 3.1, the latest release that’s been out for around two weeks now. The installation was painless and I have no real issues to report yet. The first thing I noticed was the WordPress.com style admin bar which is a feature I think many will really like. Some won’t, but there’s a number of ways to turn it off. The easiest of which is to go into your personal profile options and just turn it off or you can change it display only in the admin section.

This release features a lightning fast redesigned linking workflow which makes it easy to link to your existing posts and pages, an admin bar so you’re never more than a click away from your most-used dashboard pages, a streamlined writing interface that hides many of the seldom-used panels by default to create a simpler and less intimidating writing experience for new bloggers (visit Screen Options in the top right to get old panels back), and a refreshed blue admin scheme available for selection under your personal options.

There’s a bucket of candy for developers as well, including our new Post Formats support which makes it easy for themes to create portable tumblelogs with different styling for different types of posts, new CMS capabilities like archive pages for custom content types, a new Network Admin, an overhaul of the import and export system, and the ability to perform advanced taxonomy and custom fields queries.

As I’m writing this post and getting it ready to publish I can tell there is a definite speed increase in editor interface which is good, it was starting to get bogged down. option panels I rarely use are all minimized and can be turned off via the screen option tab to clean up the editor interface even more.

Most of the other stuff I haven’t looked at yet, but I’m excited to play around with some of the new developer features and I can’t wait to see what the various frameworks can come up with now.

If you haven’t upgraded to WordPress 3.1 yet I certainly recommend you do. As always though, be sure to backup your database first, just in case.

Teaser Images For Thesis Theme

I absolutely love the Thesis Theme framework for WordPress. Sure there’s lots of really good frameworks out there now but Thesis, in my opinion, is one of the best. However, there’s one drawback and that’s being able to dynamically add a thumbnail to a teaser post. Most themes, as well as, frameworks insist on having you add a link to a thumbnail in one of the post meta fields. This is fine, it’s also foolproof , for the most part but it’s also a step that’s annoying as all heck to me.

If you search the web there’s lots of creative solutions out there, but none really did what I wanted. Below is a sample of how I wanted to layout the main page on my site Reality Wired.

Most of the time posts have an image and with the new the_post_thumbnail function in WordPress 3.x it’s fairly easy to get this. But what if your post doesn’t contain an image? Maybe it contains a Youtube video or a Flickr image what then? Well I came up with what I think is a fairly creative solution. Here’s the code.

/* Thumbs for teasers */ 
function thesis_teaser_wp_thumb() {  
	global $post, $posts;
	
	unset ($attachments);
	unset ($video_id);
	$default_thumb =  '<img width="100" height="100" src="'.THESIS_CUSTOM_FOLDER.'/images/noimage.gif">'; 

	$args = array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID ); 
	$attachments = get_posts($args);

	// Check for a you tube video in the post and grab the video id
	preg_match('#https://[a-z]*?[\.]?youtube\.[a-z]*?/v/([\w-]*)#i', $post->post_content, $matches);
	if (!empty($matches[1])) { $video_id = $matches[1]; }

	
    if ( has_post_thumbnail() ) { 
    	the_post_thumbnail('thumbnail'); 
    } 
    elseif (!has_post_thumbnail() && isset($video_id)) {
	if(@fopen("https://img.youtube.com/vi/$video_id/default.jpg",true)) { 
		echo '<img width="100" height="100" src="https://img.youtube.com/vi/'.$video_id.'/default.jpg">';
	} else { 
		echo $default_thumb; 
	}
    	
    }
    elseif (!has_post_thumbnail() && !empty($attachments)) {
	foreach ( $attachments as $attachment ) { the_attachment_link( $attachment->ID , false ); }
    }
    else {
	echo $default_thumb;
	}
}  

To use this function in Thesis you need to first add it to your custom_functions.php file inside your thesis_18/custom directory. Next you call this function via a hook. In the case of my blog I used the thesis_hook_before_teaser_headline hook location. Add this next line somewhere in the same custom_functions.php file. (I like to keep all my hooks at the top of the file but it can really go anywhere. Some prefer to place near the function itself, it doesn’t matter.)

add_action('thesis_hook_before_teaser_headline', 'thesis_teaser_wp_thumb', '1');  

Essentially we are telling WordPress that the hook should execute right before the teaser headline is processed and the third parameter, a 1 in this case, also tells WordPress to execute this function before any other hooks in this location.

Finally I’m adding a bit of css to my custom.css file (also located in the thesis_18/custom folder).

.custom .teaser {
border-top:2px dotted #BBBBBB;
margin-top:2em;
padding-top:2em;
text-align:justify;
width:100%;
}
.custom .teasers_box {
border-top:0 none;
padding-bottom:0;
padding-top:0;
} 

.teaser img {float:left; padding-right:10px;}
a.teaser_link {float:right;clear:both;}
.format_teaser p {display:table;}
.teaser .format_teaser { margin-top:.5em; margin-bottom:.5em; }
.teaser .teaser_comments { float:right;}

Once you have this code in place it should alter your Thesis teasers to look like the sample I posted above. If you don’t like the layout just skip the css styling or customize your own. The guts you care about is the thesis_teaser_wp_thumb function. As is, the function should handle embedded Youtube videos (assuming you’re using regular embed code). So what if you want to use a different service? Well, I typically just use Youtube and it’s rather easy to get the thumbnail that Youtube generates when it encodes a video. That said, you should be able to modify this code to work with your chosen service.

// Check for a you tube video in the post and grab the video id
preg_match('#https://[a-z]*?[\.]?youtube\.[a-z]*?/v/([\w-]*)#i', $post->post_content, $matches);
if (!empty($matches[1])) { $video_id = $matches[1]; }

We use a preg_match to strip out the Youtube video id which we then insert into the code snippet below to call the thumbnail.

if(@fopen("https://img.youtube.com/vi/$video_id/default.jpg",true)) {
echo '<img src="https://img.youtube.com/vi/'.$video_id.'/default.jpg" alt="" width="100" height="100" />';
} else {
echo $default_thumb;
}

Here I check to see if the thumbnail I’m after exists and if it does I build the image code. If it doesn’t then my default thumbnail gets displayed.

I use the same process to grab thumbnails from Flickr and that code could be modified to fit other sources. At some point I turn this into a plugin but for now I thought I would share what I have. Feel free to use it, critique it or whatever.

Disable WordPress Autosave

For some time now WordPress has had this rather annoying feature called Autosave that will save copies of each edit made to a post or page at some predetermined interval. I say annoying because I don’t use it and there are numerous plugins and posts dedicated to turning this feature off. None of which seem very effective. I suppose, if you’re some kind of hardcore editor the autosave function can be a life saver, or if you tend to write 1000 word posts then having an autosave function might be worth your while, but overall it just gets annoying, not to mention how badly it clutters up your database.

For whatever reason, the WordPress 3.x series still doesn’t feature an option to turn this off via wp-admin. Not sure why. At any rate, there is a very easy way to turn the autosave feature off. All you have to do is add the following line to your wp-config.php file.

define('WP_POST_REVISIONS', false );

Add it to the bottom of your config file and save. Simple as that.

Oh and if you don’t completely want to turn it off you can also specify how many times it saves. Simply add to your wp-config.php file:

define('WP_POST_REVISIONS', 3);

where the number 3 is the amount of times you wish autosave to save your post.

WPMU Block Spam By Math plugin updated for BuddyPress

A few people using this plugin have reported that it doesn’t work with BuddyPress. After some investigation it appears to be because BuddyPress has it’s own registration template and doesn’t use some of the standard hooks WPMU uses during the initial signup process.

Not a big deal however in order to make this plugin work with the default BuddyPress theme you will have to make 1 manual edit to a theme file. I couldn’t find any better way to get the necessary check into their workflow but it’s a pretty simple edit.

Jump to the main plugin page WPMU Block Spam By Math, use the download link to get the updated plugin (version 1.1) and scroll down to the instructions and follow the note for BuddyPress users.

Post any issues in the main plugin post.