“Hiding custom fields: DO use the [is_]protected_meta filter. DON’T prefix the key with an underscore.”
— me
This post assumes you’re familiar with building plugins that rely on adding custom post meta.
Alright, so you’ve created a new custom field to store special data for a post, perhaps it looks something like this:
Simple enough. So you fill it in and save it, perhaps using code like this:
update_post_meta( $post_id, 'feelings', $_POST['post_feelings'] );
NOTE: Code samples are simplified, don’t forget to validate, sanitize, and escape user data, including your own.
But now you have a problem. “Regular” post meta shows up in the Custom Fields meta box:
This can cause several levels of confusion for users, I’ll let you imagine the ways.
One quick fix that you may be accustomed to is to change how you save the post meta. Simply prefix the meta key (“feelings”) with an underscore (“_feelings”). WordPress will automatically, with no additional effort on your part, consider that meta to be protected which will prevent it from being displayed in the Custom Fields meta box.
However, that can present its own problems.
With WordPress automatically hiding it, the meta will remain hidden even if the plugin is removed, preventing it from being edited, deleted, or otherwise managed.
Enter the is_protected_meta
filter. Keep your meta unprefixed, and use the filter to protect it.
add_filter( 'is_protected_meta', 'hide_feelings', 10, 2 );
function hide_feelings( $protected, $meta_key ) {
if ( 'feelings' == $meta_key ) return true;
return $protected;
}
Just a few lines, and you can protect your non-prefixed meta key thus keeping it from appearing in the Custom Fields meta box.
(See a mini demo plugin)
Awesome post, just added this to a plugin I’ve been working on. The
hide_feelings()
function name made me lol a little bit.Aaaaaaaaand works like a charm. Thinking back to all the times I did this the wrong way…
Thanks Kailey!
This post might be a bit old, but it helped me understanding the issue here. Thanks for that. For later readers: Nowadays you might want to use
register_post_meta( 'post', 'key_name', 'esc_attr', '__return_false' )
where you want to replace esc_attr with whatever sanitization callback you want to use.Awesome Post,It’s Working Fine. Thank’s