Action Hook since 2.0.0

add_attachment

Fires right after a new attachment is inserted

Description

add_attachment fires the moment WordPress writes a new attachment post to the database — before any image sizes or EXIF metadata have been generated. Use it to react to a new upload existing, not to read its generated data.

When it runs

Inside wp_insert_attachment(), immediately after the attachment post row is inserted. Fires on every upload, admin or programmatic.

Signature

do_action( 'add_attachment', int $post_ID );

Parameters

  • post_ID int — The ID of the newly created attachment post.

Examples

Basic

add_action( 'add_attachment', function( $post_ID ) {
    error_log( 'New attachment: ' . $post_ID );
} );

Log every new attachment as it's created.

Real case

add_action( 'add_attachment', function( $post_ID ) {
    wp_set_object_terms( $post_ID, 'unsorted', 'media_folder' );
} );

Auto-assign a default custom taxonomy term to every new upload.

Edge case

add_action( 'add_attachment', function( $post_ID ) {
    // wp_get_attachment_metadata( $post_ID ) is still empty here.
    // Hook wp_generate_attachment_metadata instead if you need sizes/EXIF.
} );

Image sizes and EXIF data don't exist yet at this point — they're built afterward.

Common Use Cases

  • Log or audit new uploads
  • Auto-tag or auto-categorize uploaded media
  • Trigger an external sync (CDN, DAM) when a file is added
  • Set default attachment meta values on creation

Common mistakes

  • Trying to read generated image sizes here — metadata isn't built yet, hook wp_generate_attachment_metadata instead
  • Confusing add_attachment with the wp_handle_upload filter — this fires after the DB post exists, not right after the file lands on disk

Related hooks

FAQ

Can I read the image dimensions inside add_attachment?

Not yet — metadata generation happens afterward. Hook wp_generate_attachment_metadata if you need sizes or EXIF data.

Does add_attachment fire for REST API uploads too?

Yes — it fires from wp_insert_attachment() regardless of whether the upload came from wp-admin, the REST API, or a programmatic call.

Source: wp-includes/post.php

Group wizard

One session: this hook, then each related_hooks entry. Walk it and tell us what to change.

add_attachment → delete_attachment → wp_generate_attachment_metadata

functions.php — add_attachment
functions.php
PHP add_attachment · Hook 1 of 3 · Step 1 of 6

Practice the add_attachment WordPress action hook in our interactive sandbox — a VS Code-style editor with a step-by-step add_attachment tutorial, add_action exercises, and instant feedback. No local WordPress install required.