Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created August 28, 2014 11:19
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 tommcfarlin/9aac216d280f62ec9c34 to your computer and use it in GitHub Desktop.
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.
<?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 );
}
}
<?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 );
}
}
<?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