Skip to content

Instantly share code, notes, and snippets.

@sebacruz
Forked from mjangda/save-post-meta-helper.php
Created November 15, 2011 10:37
Show Gist options
  • Select an option

  • Save sebacruz/1366726 to your computer and use it in GitHub Desktop.

Select an option

Save sebacruz/1366726 to your computer and use it in GitHub Desktop.
Helper function to save post meta in custom metaboxes
<?php
/**
* Saves post meta value
*
* @param int ID of the post
* @param string Name of the post_meta key (same as the $_POST key and nonce name)
* @param string Name of the nonce key
* @param mixed The default value to be assigned if not set
*
* @return string Value that was saved
*/
function my_save_option( $post_id, $option_name, $nonce_name, $default_value = '' ) {
// Grab the value from the $_POST object, or fallback to the default value
$value = isset( $_POST[$option_name] ) ? esc_attr( $_POST[$option_name] ) : $default_value;
// If nonce wasn't posted, exit out
if( ! isset( $_POST[$nonce_name] ) )
return;
// Verify the nonce
if( ! wp_verify_nonce( $_POST[$nonce_name], $option_name ) )
return;
// If we have a valid value, save it, else delete
if( $value )
update_post_meta( $post_id, $option_name, $value );
else
delete_post_meta( $post_id, $option_name );
return $value;
}
function my_save_post( $post_id ) {
// Exit out if we're autosaving
if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
// Exit out if user isn't allowed here
if( !current_user_can('edit_post', $post_id) )
return;
my_save_option( $post_id, 'my_custom_field', 'my_custom_field_nonce' );
}
add_action( 'save_post', 'my_save_post' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment