save_post not working with attachments

I’ve made a Meta Box for Posts and Pages, and while testing added Attachments too. But, curiously, the hook save_post does not fire.

$cpts = apply_filters( 'my_filter', array( 'post', 'page' ) ); // Added attachment through filter
foreach( $cpts as $pt )
{
    add_meta_box(
        'my_metabox_id',
        __( 'Meta Box' ), 
        array( $this, 'my_metabox_callback' ),
        $pt,
        'side'
    );
}
add_action( 'save_post', array( $this, 'save_metabox_data' ) );

Why is that? Isn’t attachment a Post Type too and hence subject to the same hooks as other post types?

Related posts

1 comment

  1. Not really, attachments are still not “full post types”. Manny Flerumond hints this quite well in this thread:

    Was thinking about this the past few days: currently any media files
    uploaded to a WordPress site defaults to the post status of inherit,
    which is a holdover to when media attachments were just that. Media
    was attached to a certain post, so it inherited the post’s status.
    We are starting to get away from attaching media directly to posts
    now and are even making them post like by allowing meta boxes and
    taxonomies in recent versions of WP. I think a next logical step is
    to give media post statuses other than inherit. I can think of a
    number of cases where making an image or file private could be
    useful, among other things.


    I’ve found the solution in this Stack Overflow post: “save_post” hook not working on post type attachment. We have to use the hook edit_attachment:

    add_action( 'edit_attachment', array ( $this, 'save_attachment_mb_data'), 10, 1 );
    public function save_attachment_mb_data( $post_id ) {
        // do_our_thing();
    }
    

    Note that it takes only one parameter, $post_id, so we cannot reuse the same callback as other post types. Well, unless we drop the second one ($post_object) for regular post types.

Comments are closed.