Hack: Set Default Custom Fields For New Posts

If you use custom fields, and you add some of them to each post you create, it can be a pain to manually select and add each custom field. Plus it is easy to forget. Here is a bit of code that will automatically bring up those fields and even pre-populate them with default values.

add_action('wp_insert_post', 'wpaction_custom_field_defaults');
function wpaction_custom_field_defaults($postID) {
	$post = get_post($postID);
	if ($post->post_type == 'post') {
		add_post_meta($postID, 'keywords', '', true);
	}
	return true;
}

The code works on posts only, because of the check for the post type. You could use similar code to check for other things, like the user who is logged in. So writers get pre-filled custom fields while admins don’t.

You can also add more than just one field with additional add_post_meta statements. In this example I just add one custom field, ‘keywords’, and set it to nothing. But you could also pre-fill it with something.

Leave a Reply

Your email address will not be published. Required fields are marked *