The auth_post_{$post_type}_meta_{$meta_key} WordPress PHP filter allows you to control whether a user is allowed to add post meta to a post of a given type. The dynamic portions of the hook name, $meta_key and $post_type, refer to the meta key passed to map_meta_cap() and the post type, respectively.
Usage
add_filter( 'auth_post_{$post_type}_meta_{$meta_key}', 'your_custom_function', 10, 6 );
function your_custom_function( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
// your custom code here
return $allowed;
}
Parameters
$allowed(bool): Whether the user can add the post meta. Default false.$meta_key(string): The meta key.$post_id(int): Post ID.$user_id(int): User ID.$cap(string): Capability name.$caps(array): User capabilities.
More information
See WordPress Developer Resources: auth_post_{$post_type}meta{$meta_key}
Examples
Allow adding ‘special_meta_key’ only for admins
This example allows only administrators to add the ‘special_meta_key’ to any post type.
add_filter( 'auth_post_{$post_type}_meta_special_meta_key', 'allow_special_meta_key_for_admins', 10, 6 );
function allow_special_meta_key_for_admins( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
if ( current_user_can( 'manage_options' ) ) {
return true;
}
return $allowed;
}
Disallow adding ‘_private_meta_key’ for all users
This example disallows all users from adding the ‘_private_meta_key’ to any post type.
add_filter( 'auth_post_{$post_type}_meta__private_meta_key', 'disallow_private_meta_key', 10, 6 );
function disallow_private_meta_key( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
return false;
}
Allow adding ‘rating_meta_key’ only for specific post type
This example allows users to add the ‘rating_meta_key’ only to the ‘review’ post type.
add_filter( 'auth_post_review_meta_rating_meta_key', 'allow_rating_meta_key_for_reviews', 10, 6 );
function allow_rating_meta_key_for_reviews( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
return true;
}
Allow adding ‘featured_image_meta_key’ only for specific user role
This example allows users with the ‘editor’ role to add the ‘featured_image_meta_key’ to any post type.
add_filter( 'auth_post_{$post_type}_meta_featured_image_meta_key', 'allow_featured_image_meta_key_for_editors', 10, 6 );
function allow_featured_image_meta_key_for_editors( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
$user = get_userdata( $user_id );
if ( in_array( 'editor', (array) $user->roles ) ) {
return true;
}
return $allowed;
}
Allow adding ‘location_meta_key’ only for specific user ID
This example allows only the user with ID 42 to add the ‘location_meta_key’ to any post type.
add_filter( 'auth_post_{$post_type}_meta_location_meta_key', 'allow_location_meta_key_for_specific_user', 10, 6 );
function allow_location_meta_key_for_specific_user( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) {
if ( $user_id == 42 ) {
return true;
}
return $allowed;
}