Skip to content

Instantly share code, notes, and snippets.

@chrisguitarguy
Last active May 22, 2019 16:39
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chrisguitarguy/6755748 to your computer and use it in GitHub Desktop.
Save chrisguitarguy/6755748 to your computer and use it in GitHub Desktop.
How to properly do a `save_post` callback
<?php
add_action('save_post', 'cgg_proper_save_post', 10, 2);
// first off: it doesn't matter if you return anything from this function
// `save_post` is an action, nothing is done with the return values of its
// callbacks. You're free to return $post_id if you want, obviously, but
// it's not a filter.
function cgg_proper_save_post($post_id, $post)
{
// don't do anything on autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// You only want to deal with a whitelist of post types, make sure you are
if ('some_post_type' !== $post->post_type) {
return;
}
// check the nonce: did this request come from where you expected?
// Also note that your intents (actions) should be unique to an object
// eg. wp_nonce_field('your_action' . $post_id, 'your_nonce_key', false)
if (
!isset($_POST['your_nonce_key']) ||
!wp_verify_nonce($_POST['your_nonce_key'], 'your_action' . $post_id)
) {
return;
}
// If we're here, the request is valid, make sure the user can do stuff
if (!current_user_can(get_post_type_object($post->post_type)->cap->edit_post, $post_id)) {
return;
}
if (!empty($_POST['_some_meta_key'])) {
// you might want to run the input through strip_tags or do some other validation here...
update_post_meta($post_id, '_some_meta_key', $_POST['_some_meta_key']);
} else {
// if it's empty, delete it.
delete_post_meta($post_id, '_some_meta_key');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment