Skip to content

Instantly share code, notes, and snippets.

@scofennell
Last active June 20, 2017 16:06
Show Gist options
  • Save scofennell/ec86c5106377f02162d3 to your computer and use it in GitHub Desktop.
Save scofennell/ec86c5106377f02162d3 to your computer and use it in GitHub Desktop.
WordPress function to save custom meta box for attachment posts
<?php
/**
* Save the Data
*
*/
function sjf_deh_save_custom_meta( $post_id ) {
// Check if the nonce exists.
if( ! isset( $_POST[ 'sjf_deh_custom_meta_box_nonce' ] ) ) { return $post_id; }
// Check if the nonce is valid.
if( ! wp_verify_nonce( $_POST[ 'sjf_deh_custom_meta_box_nonce' ], basename( __FILE__ ) ) ) { return $post_id; }
// Dont' bother trying to do this if it's an autosave
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return $post_id; }
// Check user permissions
if ( !current_user_can( 'edit_page', $post_id) ) { return $post_id; }
// Get the meta fields.
$sjf_deh_meta_fields = sjf_deh_meta_fields();
// Loop through fields and save the data.
foreach ($sjf_deh_custom_meta_fields as $field) {
// Get the old value for this meta key.
$old = get_post_meta($post_id, $field['id'], true);
// Get and sanitize the posted value for this meta key
$new = sanitize_text_field( $_POST[ $field['id'] ] );
// If the new value is different, update the old value.
if ( $new && $new != $old ) {
update_post_meta($post_id, $field['id'], $new);
// If the new value is present and empty, delete the old value.
} elseif ( '' == $new && $old ) {
delete_post_meta( $post_id, $field['id'], $old );
}
} // end foreach meta field
}
add_action( 'edit_attachment', 'sjf_deh_save_custom_meta' );
add_action( 'add_attachment', 'sjf_deh_save_custom_meta' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment