Access to custom fields (post meta)

This post is about access to post custom fields or post meta data. User interface is presented at post editor page by “Custom Fields” meta box:

custom fields
Custom Fields

If user does not see “Custom Fields” meta box, first look at the same named checkbox at the “Screen Options”:

screen options - custom fields
Screen Options – Custom Fields

List of custom fields available for current user for editing and selection may vary. Script takes from the database just the 30 items by default. It’s possible to increase this value via custom ‘postmeta_form_limit’ filter. Like this:

add_filter('postmeta_form_limit', 'ure_postmeta_form_limit', 10, 1);
function ure_postmeta_form_limit($limit) {

    $limit = 60;
    return $limit;
}

List of available items may also depend from a protection applied to the custom field.
1st, WordPress checks if current user can edit this post, so user should can ‘edit_posts’, ‘edit_published_posts’ – for post in the ‘Published’ state, ‘edit_others_posts’ – for the post created by other user.
2nd, WordPress applies a custom filter: “auth_{$object_type}_meta_{$meta_key}”. For example, is $object_type = ‘post’ and $meta_key = ‘ure_post_access_error_message’, filter will be ‘auth_post_meta_ure_post_access_error_message’. Example of PHP code for such filter:

add_filter('auth_post_meta_ure_post_access_error_message', 'ure_auth_post_meta', 10, 6);
// block access to URE's post meta (custom) fields, if user does not have enough permissions
public function ure_auth_post_meta($allowed, $meta_key, $post_id, $user_id, $cap, $caps) {
        
   $allowed = current_user_can('ure_view_posts_access');
        
   return $allowed;        
}

3rd, If WordPress sees that current user is not allowed to work with this custom field after 1st two steps, it checks if user can not existing user capability, for example: ‘edit_post_meta’. Thus, it’s possible to grant to a user without administrator permissions full access to any meta field. It’s enough just to grant him the list of capabilities not created by WordPress by default:
‘edit_post_meta’, ‘delete_post_meta’, ‘add_post_meta’, ‘edit_comment_meta’, ‘delete_comment_meta’, ‘add_comment_meta’, ‘edit_term_meta’, ‘delete_term_meta’, ‘add_term_meta’, ‘edit_user_meta’, ‘delete_user_meta’, ‘add_user_meta’. (This list was taken from the file wp-includes/capabilities.php, function map_meta_cap()).

I recommend to use this user capabilities with care, as there are custom fields for internal use only, which is specially protected from unauthorized access. So do not grant accidentally undesired access to the not authorized person.

Share