Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Irfan-Ansari/9505353 to your computer and use it in GitHub Desktop.
Save Irfan-Ansari/9505353 to your computer and use it in GitHub Desktop.
<?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 = '', $sanitize_callback = 'sanitize_text_field' ) {
// Grab the value from the $_POST object, or fallback to the default value
$value = isset( $_POST[$option_name] ) ? $_POST[$option_name] : $default_value;
if ( ! is_callable( $sanitize_callback ) )
$sanitize_callback = 'sanitize_text_field';
if ( is_array( $value ) )
$value = array_map( $sanitize_callback, $value );
else
$value = call_user_func( $sanitize_callback, $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