Using WordPress ‘delete_{$meta_type}_metadata_by_mid’ PHP filter

The delete_{$meta_type}_metadata_by_mid WordPress PHP filter short-circuits deleting metadata of a specific type by meta ID. The dynamic portion, $meta_type, refers to the meta object type (post, comment, term, user, or any other type with an associated meta table).

Usage

add_filter( 'delete_post_metadata_by_mid', 'my_custom_function', 10, 2 );

function my_custom_function( $delete, $meta_id ) {
  // your custom code here
  return $delete;
}

Parameters

  • $delete: null|bool – Whether to allow metadata deletion of the given type.
  • $meta_id: int – Meta ID.

More information

See WordPress Developer Resources: delete_{$meta_type}_metadata_by_mid

Examples

Prevent post metadata deletion for a specific meta ID

Prevents the deletion of post metadata with meta ID 100.

add_filter( 'delete_post_metadata_by_mid', 'prevent_meta_id_100_deletion', 10, 2 );

function prevent_meta_id_100_deletion( $delete, $meta_id ) {
  if ( $meta_id == 100 ) {
    return false;
  }
  return $delete;
}

Allow metadata deletion only for users with a specific capability

Allows metadata deletion only for users with the ‘manage_options’ capability.

add_filter( 'delete_post_metadata_by_mid', 'restrict_meta_deletion_by_capability', 10, 2 );

function restrict_meta_deletion_by_capability( $delete, $meta_id ) {
  if ( current_user_can( 'manage_options' ) ) {
    return $delete;
  }
  return false;
}

Log metadata deletion attempts for a specific meta type

Logs metadata deletion attempts for the ‘post’ meta type.

add_filter( 'delete_post_metadata_by_mid', 'log_meta_deletion_attempts', 10, 2 );

function log_meta_deletion_attempts( $delete, $meta_id ) {
  error_log( "User attempted to delete post metadata with meta ID: " . $meta_id );
  return $delete;
}

Prevent metadata deletion for a specific term meta type

Prevents the deletion of term metadata with meta ID 50.

add_filter( 'delete_term_metadata_by_mid', 'prevent_term_meta_id_50_deletion', 10, 2 );

function prevent_term_meta_id_50_deletion( $delete, $meta_id ) {
  if ( $meta_id == 50 ) {
    return false;
  }
  return $delete;
}

Prevent metadata deletion for a specific user meta type

Prevents the deletion of user metadata with meta ID 200.

add_filter( 'delete_user_metadata_by_mid', 'prevent_user_meta_id_200_deletion', 10, 2 );

function prevent_user_meta_id_200_deletion( $delete, $meta_id ) {
  if ( $meta_id == 200 ) {
    return false;
  }
  return $delete;
}