-
-
Save tommcfarlin/9aac216d280f62ec9c34 to your computer and use it in GitHub Desktop.
[WordPress] A strategy for saving post meta data when there's only actual data to save, and retrieving the information only if there's something to retrieve.
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', 'acme_save_post_meta_data' ); | |
/** | |
* Saves the incoming $_POST data to the post meta data (with the post | |
* identified by the incoming ID) if and only if the value of the | |
* data isn't empty. | |
* | |
* Authorisation, authentication and sanitization omitted for brevity. | |
* | |
* @param int $post_id The associated post ID | |
*/ | |
function acme_save_post_meta_data( $post_id ) { | |
$meta_value = $_POST['post-key']; | |
if ( isset( $meta_value ) ) { | |
add_post_meta( $post_id, 'acme_post_meta_key', $meta_value ); | |
} | |
} |
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', 'acme_save_post_meta_data' ); | |
/** | |
* Saves the incoming $_POST data to the post meta data (with the post | |
* identified by the incoming ID) if and only if the value of the | |
* data isn't empty. | |
* | |
* Authorisation, authentication and sanitization omitted for brevity. | |
* | |
* @param int $post_id The associated post ID | |
*/ | |
function acme_save_post_meta_data( $post_id ) { | |
$meta_value = $_POST['post-key']; | |
if ( isset( $meta_value ) && 0 < strlen( trim( $meta_value ) ) ) { | |
add_post_meta( $post_id, 'acme_post_meta_key', $meta_value ); | |
} | |
} |
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 | |
/** | |
* Retrieving the meta data associated with the 'acme_post_meta' key for | |
* the specified $post_id. | |
* | |
* If no value is found, then null will be returned. | |
* | |
* @param int $post_id The associated post ID | |
* @return The value; otherwise, null | |
*/ | |
function acme_get_post_meta_data( $post_id ) { | |
$value = get_post_meta( $post_id, 'acme_post_meta_key', false ); | |
return empty( $value ) ? null : $value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment