Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save BobbyAdamson/0063b35bcd070d8ea38f to your computer and use it in GitHub Desktop.
Save BobbyAdamson/0063b35bcd070d8ea38f to your computer and use it in GitHub Desktop.
Addressing problem with Smashing Magazine's Custom Post Type guide: http://www.smashingmagazine.com/2012/11/08/complete-guide-custom-post-types/
function product_price_box_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'product_price_box_content_nonce' );
$meta_values = get_post_meta($post->ID, 'product_price', true);
echo '<label for="product_price"></label>';
if($meta_values != '') {
echo '<input type="text" id="product_price" name="product_price" placeholder="enter a price" value="' . $meta_values . '"/>';
} else {
echo '<input type="text" id="product_price" name="product_price" placeholder="enter a price"/>';
}
}
@BobbyAdamson
Copy link
Author

My original comment from Smashing Magazine's post regarding this:

Developers using this code (supplied by Smashing Magazine) will have an issue with custom meta boxes not saving content on submit or update. In fact, the content is being saved, but the custom meta box is not displaying the information that is saved to it. The issue there is that if a user goes in to the post and edits it without re-entering the custom meta content; the box will stay empty and save a null value over the previously entered content. This requires the user to re-enter the same content each time they edit the post.

The solution is similar to what Tim wrote above me, but written out a little more to understand what’s going on easier (also Tim’s solution did not work for me.) First, in the “product_price_box_content” function, create a $meta_value variable that stores the meta data like so: $meta_values = get_post_meta($post->ID, ‘product_price’, true);

Then after the label for the product price, write an if statement. If ($meta_values != ”) { echo the input with value=”‘ . $meta_values . ‘” (or whatever you’ve chosen to name your meta value variable) }
else { echo the input with no value }

This conditional asks “Is $meta_values a non-null value?” meaning has there been content saved to this meta box before? If yes, then echo the input box with the content that has been entered before as the default value of the box. This verifies that your content has been saved, and makes it unnecessary to re-enter the same content each time you edit your post.

If the answer is no – meaning either this is the creation of the current post, or the post is being edited and a value was not entered for this meta box before, then echo the input with no default value.

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