The auth_post_meta_{$meta_key} WordPress PHP filter allows you to control whether a user is allowed to add post meta to a post, based on the meta key.
Usage
add_filter( 'auth_post_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 is 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_meta_{$meta_key}
Examples
Allow users to add specific post meta
Allow users with the ‘editor’ role to add a ‘featured’ post meta.
add_filter( 'auth_post_meta_featured', 'allow_featured_meta', 10, 6 ); function allow_featured_meta( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) { $user = get_userdata( $user_id ); if ( in_array( 'editor', $user->roles ) ) { $allowed = true; } return $allowed; }
Prevent users from adding a post meta
Prevent users from adding a ‘restricted’ post meta.
add_filter( 'auth_post_meta_restricted', 'prevent_restricted_meta', 10, 6 ); function prevent_restricted_meta( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) { return false; }
Check user capabilities
Allow users with the ‘manage_options’ capability to add a ‘custom’ post meta.
add_filter( 'auth_post_meta_custom', 'allow_custom_meta', 10, 6 ); function allow_custom_meta( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) { if ( current_user_can( 'manage_options', $user_id ) ) { $allowed = true; } return $allowed; }
Allow post meta based on post type
Allow users to add a ‘rating’ post meta only for ‘review’ post types.
add_filter( 'auth_post_meta_rating', 'allow_rating_meta', 10, 6 ); function allow_rating_meta( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) { $post = get_post( $post_id ); if ( 'review' === $post->post_type ) { $allowed = true; } return $allowed; }
Custom condition for adding post meta
Allow users to add a ‘special’ post meta if they have a specific user meta value.
add_filter( 'auth_post_meta_special', 'allow_special_meta', 10, 6 ); function allow_special_meta( $allowed, $meta_key, $post_id, $user_id, $cap, $caps ) { $user_special = get_user_meta( $user_id, 'is_special', true ); if ('1' === $user_special ) { $allowed = true; } return $allowed; }