Last active
August 29, 2015 13:56
-
-
Save tivnet/9262682 to your computer and use it in GitHub Desktop.
save_post action example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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