1

Just wondering what the best way to save postmeta is.

I don't want empty postmeta values clogging up the database.

I had already been saving postmeta in my plugin, which was adding empty values, so I'd like to clean those up as people re-save their posts.

Any opinions on doing it like this? Improvements?:

if ( isset( $_POST[ '_my_meta_key' ] ) && $_POST[ '_my_meta_key' ] !== '' ) {
    update_post_meta( $post_id, '_my_meta_key', $_POST[ '_my_meta_key' ] );
} else {
    delete_post_meta( $post_id, '_my_meta_key' );
}
2
  • It depends.. If you edit your post, do you use get_post_meta() and output it in input? If you did it the wrong way and if input is empty every time you'll update the post but there's a value in database, you'll lose it. Otherwise your code works just fine. PS! We have no means to test it in your environment. Use this code with one input, make a dummy post, try to update it and see what happens in your database.
    – N00b
    Commented Mar 16, 2016 at 1:31
  • When the input is saved, I use get_post_meta() in the input to display the saved value. In that case, nothing inherently wrong doing it like the above? Open to other options that have been used in the wild before, I just wrote the above without poking around too much. Thanks! Commented Mar 16, 2016 at 1:36

1 Answer 1

4

Your approach is good, you should run a basic check against the data tough. Otherwise you might get an array or a serialized object … which might lead to unexpected consequences (including security issues!) when you or someone else is trying to print the values.

Maybe something like this is easier:

$key   = '_my_meta_key';
$value = filter_input( INPUT_POST, $key, FILTER_SANITIZE_STRING );

if ( $value )
    update_post_meta( $post_id, $key, $value );
else
    delete_post_meta( $post_id, $key );

Note that you should avoid writing the key string more than once. If you ever want to change its name, you should have as few places to search for it as possible. Ideally, just one in your whole code base.

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.