Last active
January 26, 2017 09:08
-
-
Save sergeliatko/21ad4475831b141d0a6a498c6f019d65 to your computer and use it in GitHub Desktop.
Saves post meta in WordPress
This file contains hidden or 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 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 ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please note: this function does not save integer zero value (nothing that returns true on empty() check)