Skip to content

Instantly share code, notes, and snippets.

@tivnet
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tivnet/9262682 to your computer and use it in GitHub Desktop.
Save tivnet/9262682 to your computer and use it in GitHub Desktop.
save_post action example
<?php
add_action( 'save_post', 'tivwp_save_post', 10, 3 );
/**
* Save the selected template info for the particular post
* @param int $post_id
* @param \WP_Post $post
* @param bool $update
* @wp-hook save_post
*/
function tivwp_save_post( $post_id, \WP_Post $post, $update ) {
// Verify if this is an auto save routine.
// If it is then our form has not been submitted, so we don't want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
if ( ! $update ) {
return;
}
if ( $post->post_type !== 'post' ) { // could be a CPT, for example 'product'
return;
}
// Check permissions
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return;
}
/**
* @todo
* Check for the post status: published, draft, ...
* Maybe we do not need to do anything if it goes to trash?
*/
/**
* IF THAT WAS A METABOX, WE SHOULD HAVE SOME NONCES (name and action)
* Verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times
*/
if (
empty( $_POST[TIVWP_NONCE_METABOX_NAME] )
or ! wp_verify_nonce( $_POST[TIVWP_NONCE_METABOX_NAME], TIVWP_NONCE_METABOX_ACTION )
) {
return;
}
// Sanitize user input.
$somevar = sanitize_text_field( $_POST['somevar'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_somevar', array( 'somevar' => $somevar ) );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment