The added_{$meta_type}_meta WordPress PHP action fires immediately after meta of a specific type is added. The dynamic portion of the hook name, $meta_type, refers to the meta object type (post, comment, term, user, or any other type with an associated meta table).
Usage
add_action('added_{$meta_type}_meta', 'your_custom_function', 10, 4);
function your_custom_function($mid, $object_id, $meta_key, $_meta_value) {
// Your custom code here
return $mid;
}
Parameters
$mid(int): The meta ID after a successful update.$object_id(int): ID of the object metadata is for.$meta_key(string): Metadata key.$_meta_value(mixed): Metadata value.
More information
See WordPress Developer Resources: added_{$meta_type}_meta
Examples
Log added post meta
Log whenever a post meta is added.
add_action('added_post_meta', 'log_added_post_meta', 10, 4);
function log_added_post_meta($mid, $post_id, $meta_key, $meta_value) {
// Log added post meta
error_log("Post meta added: {$mid}, {$post_id}, {$meta_key}, {$meta_value}");
}
Notify admin when a user meta is added
Send an email to the admin when a specific user meta is added.
add_action('added_user_meta', 'notify_admin_user_meta_added', 10, 4);
function notify_admin_user_meta_added($mid, $user_id, $meta_key, $meta_value) {
if ('custom_meta_key' === $meta_key) {
$admin_email = get_option('admin_email');
wp_mail($admin_email, 'User Meta Added', "User ID: {$user_id}, Meta key: {$meta_key}, Meta value: {$meta_value}");
}
}
Update term meta cache
Update term meta cache when a term meta is added.
add_action('added_term_meta', 'update_term_meta_cache', 10, 4);
function update_term_meta_cache($mid, $term_id, $meta_key, $meta_value) {
wp_cache_delete($term_id, 'term_meta');
}
Add default comment meta
Add a default comment meta when a new comment meta is added.
add_action('added_comment_meta', 'add_default_comment_meta', 10, 4);
function add_default_comment_meta($mid, $comment_id, $meta_key, $meta_value) {
if ('custom_comment_meta' !== $meta_key) {
add_comment_meta($comment_id, 'custom_comment_meta', 'default_value');
}
}
Validate custom post meta
Validate custom post meta before it is added.
add_action('added_post_meta', 'validate_custom_post_meta', 10, 4);
function validate_custom_post_meta($mid, $post_id, $meta_key, $meta_value) {
if ('custom_post_meta' === $meta_key && !validate_custom_value($meta_value)) {
delete_metadata_by_mid('post', $mid);
}
}
function validate_custom_value($value) {
// Validation logic here
return true; // or false, based on the validation
}