Well, changing get_post( $post_ID )->post_title
to get_the_title($page->ID)
won’t work, because the variable $page
isn’t defined anywhere in your function…
If you’ll take a look at add_attachment
hook, then you’ll see that it takes only one parameter:
$post_ID – (int) Attachment ID.
So you don’t have the ID of post that it’s attached to. And to be honest, you can’t have such post, because the attachment can be uploaded directly in Media Library, so it won’t be attached to any post…
But the add_attachment
action is called when the post is already in DB, so you can get it’s parent (and if attachment was uploaded to some post, then that post will be set as parent).
So something like this might work:
add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
function my_set_image_meta_upon_image_upload( $post_ID ) {
// Check if uploaded file is an image, else do nothing
if ( wp_attachment_is_image( $post_ID ) ) {
$attachment = get_post( $post_ID );
$my_image_title = $attachment->post_title;
if ( $attachment->post_parent ) { // if it has parent, use it's title instead
$my_image_title = get_post_field( 'post_title', $attachment->post_parent );
}
... // rest of the code
wp_update_post( $my_image_meta );
}
}