Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
genesis_save_custom_fields function for saving meta box data http://wpsites.net/web-design/hand-coded-meta-box-for-genesis/
/**
* Save post meta / custom field data for a post or page.
*
* It verifies the nonce, then checks we're not doing autosave, ajax or a future post request. It then checks the
* current user's permissions, before finally* either updating the post meta, or deleting the field if the value was not
* truthy.
*
* By passing an array of fields => values from the same metabox (and therefore same nonce) into the $data argument,
* repeated checks against the nonce, request and permissions are avoided.
*
* @since 1.9.0
*
* @param array $data Key/Value pairs of data to save in '_field_name' => 'value' format.
* @param string $nonce_action Nonce action for use with wp_verify_nonce().
* @param string $nonce_name Name of the nonce to check for permissions.
* @param WP_Post|integer $post Post object or ID.
* @param integer $deprecated Deprecated (formerly accepted a post ID).
*
* @return mixed Return null if permissions incorrect, doing autosave, ajax or future post, false if update or delete
* failed, and true on success.
*/
function genesis_save_custom_fields( array $data, $nonce_action, $nonce_name, $post, $deprecated = null ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.0.0' );
}
//* Verify the nonce
if ( ! isset( $_POST[ $nonce_name ] ) || ! wp_verify_nonce( $_POST[ $nonce_name ], $nonce_action ) )
return;
//* Don't try to save the data under autosave, ajax, or future post.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
return;
if ( defined( 'DOING_CRON' ) && DOING_CRON )
return;
//* Grab the post object
if ( ! is_null( $deprecated ) )
$post = get_post( $deprecated );
else
$post = get_post( $post );
//* Don't save if WP is creating a revision (same as DOING_AUTOSAVE?)
if ( 'revision' === get_post_type( $post ) )
return;
//* Check that the user is allowed to edit the post
if ( ! current_user_can( 'edit_post', $post->ID ) )
return;
//* Cycle through $data, insert value or delete field
foreach ( (array) $data as $field => $value ) {
//* Save $value, or delete if the $value is empty
if ( $value )
update_post_meta( $post->ID, $field, $value );
else
delete_post_meta( $post->ID, $field );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.