Using WordPress ‘add_attachment’ PHP action

The add_attachment WordPress PHP action fires when an attachment is added to a post.

Usage

add_action('add_attachment', 'your_function_name');
function your_function_name($post_id) {
    // your custom code here
}

Parameters

  • $post_id (int): The ID of the attachment.

More information

See WordPress Developer Resources: add_attachment

Examples

Add a custom metadata to an attachment

Automatically add custom metadata when an attachment is added.

add_action('add_attachment', 'add_custom_metadata');
function add_custom_metadata($post_id) {
    add_post_meta($post_id, 'custom_meta_key', 'custom_meta_value', true);
}

Send an email notification when an attachment is added

Send an email notification to the admin when a new attachment is added.

add_action('add_attachment', 'send_email_notification');
function send_email_notification($post_id) {
    $admin_email = get_option('admin_email');
    $subject = 'New Attachment Added';
    $message = 'A new attachment with ID ' . $post_id . ' has been added.';
    wp_mail($admin_email, $subject, $message);
}

Log attachment addition

Log attachment addition events in a custom log file.

add_action('add_attachment', 'log_attachment_addition');
function log_attachment_addition($post_id) {
    $log_message = 'Attachment with ID ' . $post_id . ' added on ' . date('Y-m-d H:i:s') . PHP_EOL;
    error_log($log_message, 3, '/path/to/your/attachment_log.txt');
}

Set attachment title based on file name

Automatically set the attachment title based on its file name.

add_action('add_attachment', 'set_attachment_title');
function set_attachment_title($post_id) {
    $file_name = basename(get_attached_file($post_id));
    $new_title = preg_replace('/\.[^.]+$/', '', $file_name);
    wp_update_post(array('ID' => $post_id, 'post_title' => $new_title));
}

Add an attachment to a specific category

Automatically add an attachment to a specific category when it is added.

add_action('add_attachment', 'assign_attachment_category');
function assign_attachment_category($post_id) {
    $category_id = 10; // The ID of the category you want to add the attachment to
    wp_set_object_terms($post_id, $category_id, 'category');
}