Skip to content

Instantly share code, notes, and snippets.

@sergeliatko
Last active January 26, 2017 09:08
Show Gist options
  • Save sergeliatko/21ad4475831b141d0a6a498c6f019d65 to your computer and use it in GitHub Desktop.
Save sergeliatko/21ad4475831b141d0a6a498c6f019d65 to your computer and use it in GitHub Desktop.
Saves post meta in WordPress
<?php
/** add save_post_meta to save_post hook */
add_action( 'save_post', 'save_post_meta', 10, 3 );
/**
* Saves post meta.
*
* @param $post_ID
* @param WP_Post $post
* @param $update
*
*/
function save_post_meta( $post_ID, WP_Post $post, $update ) {
/** process only if update and not autosave and the nonce is verified */
if(
( true === $update )
&& !( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
&& ( isset( $_REQUEST['_wpnonce'] ) && wp_verify_nonce( $_REQUEST['_wpnonce'], 'update-post_' . $post_ID ) )
) {
/** @var array $fields to save */
$fields = array(
'_hide_content_widgets' => array(
'absint'
)
);
/**
* @var string $field to save
* @var array $sanitizers array of functions to use to sanitize the submitted value
*/
foreach ( $fields as $field => $sanitizers ) {
/** if not submitted - delete post meta and do next field */
if( !isset( $_POST[ $field ] ) ) {
delete_post_meta( $post_ID, $field );
continue;
}
/** @var mixed $value submitted */
$value = $_POST[ $field ];
/** @var callable $sanitizer */
foreach ( $sanitizers as $sanitizer ) {
$value = call_user_func( $sanitizer, $value );
}
/** save/delete post meta */
empty( $value ) ? delete_post_meta( $post_ID, $field ) : update_post_meta( $post_ID, $field, $value );
}
}
}
@sergeliatko
Copy link
Author

Please note: this function does not save integer zero value (nothing that returns true on empty() check)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment