Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to properly do a `save_post` callback
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
// You only want to deal with a whitelist of post types, make sure you are
if ('some_post_type' !== $post->post_type) {
// 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)
) {
// 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)) {
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
You can’t perform that action at this time.