WordPress meta box values display to custom fields

I’ve added meta boxes to my posts using the action “add_meta_boxes” to add/change custom settings like background-color, etc.

When I enable the custom fields in my screen options, all values of my meta boxes are displayd in these custom fields!

Read More

There are also showing up in the selectbox to add a new “custom field”.

Related posts

Leave a Reply

2 comments

  1. If you want to hide your post meta data from custom fields metabox, you should start your meta keys with underscore. Example _background-color

    Added:

    Also you can use is_protected_meta filter, which return boolean value (true - hide, false - show).

    Filter parameters: $protected, $meta_key. See wp-includes/meta.php file. function is_protected_meta()

  2. Normally WP hides meta keys that start with an underscore/_ from the Custom Fields (default/core) MetaBox.

    Now imagine that you do not want to give the user of your plugin the possibility to alter Post Meta Data through the ugly and user unfriendly Custom Fields meta box. And therefore you build a custom meta box and prefix your meta key with an underscore/_. Then the user changes his mind and deactivates or uninstalls your plugin. What happens now is that the user has exactly no access to any UI to alter the (still present) meta data. This is a really, really bad situation for the user.

    So we need a switch to turn off the Custom Fields MetaBox access as long as your plugin is activated. Therefore WP Core got the is_protected_meta() function. It basically consists out of two lines of code:

    $protected = ( '_' == $meta_key[0] );
    return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type );
    

    As it’s not nice to only offer a filter to handle that, WordPress today has a simple function that you can use:

    register_meta( $meta_type, $key, $sanitize_callback, $auth_callback );
    

    And the last argument, the $auth_callback does the following inside this function:

    if ( empty( $auth_callback ) ) {
        if ( is_protected_meta( $meta_key, $meta_type ) )
            $auth_callback = '__return_false';
        else
            $auth_callback = '__return_true';
    }
    
    if ( is_callable( $auth_callback ) )
        add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 );
    

    As you can see, you want to just add '__return_false' as $auth_callback to deactivate Custom Fields MetaBox access as long as your plugin is active. When the user removes or deactivates your plugin, he instantly has access to the meta field via the standard Custom Fields MetaBox.


    Notes: WP core at v4.0.1 while writing this question. Make use of the $sanitize_callback! Thanks to Trepmal for posting about the is_protected_meta filter on her blog. Else I would have never stumbled upon the use case for that.