Using WordPress ‘add_{$meta_type}_meta’ PHP action

The add_{$meta_type}_meta WordPress PHP action fires immediately before 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('add_post_meta', 'your_custom_function', 10, 3);
function your_custom_function($object_id, $meta_key, $_meta_value) {
    // your custom code here
}

Parameters

  • $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: add_{$meta_type}_meta

Examples

Validate post meta before adding

Check if the meta key is ‘price’ and ensure the value is a positive number before adding.

add_action('add_post_meta', 'validate_price_meta', 10, 3);
function validate_price_meta($object_id, $meta_key, $_meta_value) {
    if ($meta_key === 'price' && (!is_numeric($_meta_value) || $_meta_value < 0)) {
        return false;
    }
}

Log added post meta

Log added post meta to a custom log file.

add_action('add_post_meta', 'log_added_post_meta', 10, 3);
function log_added_post_meta($object_id, $meta_key, $_meta_value) {
    error_log("Added meta: {$meta_key} => {$_meta_value} for post {$object_id}", 3, '/path/to/your_log_file.log');
}

Set default post thumbnail

Set a default post thumbnail when a new post is created and no featured image is set.

add_action('add_post_meta', 'set_default_thumbnail', 10, 3);
function set_default_thumbnail($object_id, $meta_key, $_meta_value) {
    if ($meta_key === '_thumbnail_id' && empty($_meta_value)) {
        update_post_meta($object_id, '_thumbnail_id', 'your_default_thumbnail_id');
    }
}

Sanitize user meta

Sanitize user meta data before it is added to the database.

add_action('add_user_meta', 'sanitize_user_meta', 10, 3);
function sanitize_user_meta($object_id, $meta_key, $_meta_value) {
    if ($meta_key === 'custom_user_data') {
        $_meta_value = sanitize_text_field($_meta_value);
    }
}

Add custom term meta

Add custom term meta data for a new term.

add_action('add_term_meta', 'add_custom_term_meta', 10, 3);
function add_custom_term_meta($object_id, $meta_key, $_meta_value) {
    if ($meta_key === 'custom_term_data') {
        $_meta_value = 'your_custom_data';
    }
}