Retain custom fields when restoring a previous post version in WordPress

This little script will keep whatever custom field values you have used when you restore a post to a previous version. Currently, WordPress by default will clear those custom fields whenever you try to restore a post to a previous version which can lead to some headaches.  Add this bit to your functions.php file to keep those fields when you restore:

global $tempholder;
function customfields_save_post( $post_id ) {
global $templholder;
$parent_id = wp_is_post_revision( $post_id );
if ( $parent_id ) {
$parent = get_post( $parent_id );
$templholder = get_post_custom($parent->ID);
}
}
add_action( 'save_post', 'customfields_save_post' );
function customfields_restore_revision( $post_id, $revision_id ) {
global $templholder;
foreach($templholder as $index => $item) {
delete_post_meta($post_id, $index);
if ($item[0] != '') {
add_post_meta($post_id, $index, $item[0]);
}
}
}
add_action( 'wp_restore_post_revision', 'customfields_restore_revision', 10, 2 );