Using WordPress ‘add_{$meta_type}_metadata’ PHP filter

The add_{$meta_type}_metadata WordPress PHP filter allows you to short-circuit adding metadata of a specific type. The dynamic part 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). Returning a non-null value will effectively short-circuit the function.

Usage

add_filter('add_post_metadata', 'my_custom_function', 10, 5);

function my_custom_function($check, $object_id, $meta_key, $meta_value, $unique) {
    // Your custom code here

    return $check;
}

Parameters

  • $check (null|bool) – Whether to allow adding metadata for the given type.
  • $object_id (int) – ID of the object metadata is for.
  • $meta_key (string) – Metadata key.
  • $meta_value (mixed) – Metadata value. Must be serializable if non-scalar.
  • $unique (bool) – Whether the specified meta key should be unique for the object.

More information

See WordPress Developer Resources: add_{$meta_type}_metadata

Examples

Prevent adding specific metadata to posts

This example prevents adding metadata with the key ‘restricted_key’ to posts.

add_filter('add_post_metadata', 'prevent_restricted_key', 10, 5);

function prevent_restricted_key($check, $object_id, $meta_key, $meta_value, $unique) {
    if ($meta_key === 'restricted_key') {
        return false;
    }
    return $check;
}

Allow only unique metadata values for a specific key

This example ensures that the metadata key ‘unique_key’ has only unique values for each post.

add_filter('add_post_metadata', 'unique_key_metadata', 10, 5);

function unique_key_metadata($check, $object_id, $meta_key, $meta_value, $unique) {
    if ($meta_key === 'unique_key') {
        return true;
    }
    return $check;
}

Add metadata only to posts with a specific author

This example allows adding metadata only to posts with a specific author (author ID 10 in this case).

add_filter('add_post_metadata', 'restrict_metadata_to_author', 10, 5);

function restrict_metadata_to_author($check, $object_id, $meta_key, $meta_value, $unique) {
    $post = get_post($object_id);
    if ($post->post_author == 10) {
        return $check;
    }
    return false;
}

Prevent adding empty metadata values

This example prevents adding metadata with empty values.

add_filter('add_post_metadata', 'prevent_empty_metadata', 10, 5);

function prevent_empty_metadata($check, $object_id, $meta_key, $meta_value, $unique) {
    if (empty($meta_value)) {
        return false;
    }
    return $check;
}

Add metadata only to published posts

This example allows adding metadata only to published posts.

add_filter('add_post_metadata', 'restrict_metadata_to_published', 10, 5);

function restrict_metadata_to_published($check, $object_id, $meta_key, $meta_value, $unique) {
    $post = get_post($object_id);
    if ($post->post_status === 'publish') {
        return $check;
}
return false;
}