I have added a custom field "Buy Now" link on media edit page but I am not able to save that data like other post types. Is there any other hook which is triggered after add/edit/update media/attachment?

I am using this function:

function update_attachment_extra_info( $post_id ) {

   // code to update data

add_action( 'save_post', 'update_attachment_extra_info' );

But this hook is not triggered.

  • Could you please edit your question and include the code that adds the Buy Now field? – Dave Romsey Feb 14 '17 at 21:13
  • Actually, I am using save_post hook but when I try to update , this hook was not called. – shishir mishra Feb 14 '17 at 21:16
  • The hooks attachment_fields_to_edit, edit_attachment, and wp_ajax_save-attachment-compat are what you'll need. The code from this question works, and can easily be adapted: wordpress.stackexchange.com/questions/180092/… – Dave Romsey Feb 14 '17 at 21:24
  • Happy to help! I reviewed the code from the question I linked a bit closer and found that the non-ajax part was not correct, so I added the revised code as an answer. – Dave Romsey Feb 14 '17 at 21:56

Here is an example that adds a custom media field named Buy Now. This example saves the value of the custom field on the media overlay screen via ajax, as well as the media edit screen (non ajax).

 * Add custom field to media
add_filter( 'attachment_fields_to_edit', 'wpse256463_attachment_fields', 10, 2 );
function wpse256463_attachment_fields( $fields, $post ) {
    $meta = get_post_meta( $post->ID, 'buy_now', true );
    $fields['buy_now'] = array(
            'label' =>  __( 'Buy Now', 'text-domain' ),
            'input' => 'text',
            'value' => $meta,
            'show_in_edit' => true,

    return $fields;         

 * Update custom field within media overlay (via ajax)
add_action( 'wp_ajax_save-attachment-compat', 'wpse256463_media_fields', 0, 1 );
function wpse256463_media_fields() {
    $post_id = $_POST['id'];
    $meta = $_POST['attachments'][ $post_id ]['buy_now'];
    update_post_meta( $post_id , 'buy_now', $meta );

    clean_post_cache( $post_id );

 * Update media custom field from edit media page (non ajax).
add_action( 'edit_attachment', 'wpse256463_update_attachment_meta', 1 );
function wpse256463_update_attachment_meta( $post_id ) {
    $buy_now = isset( $_POST['attachments'][ $post_id ]['buy_now'] ) ? $_POST['attachments'][ $post_id ]['buy_now'] : false;
    update_post_meta( $post_id, 'buy_now', $buy_now );
  • 1
    thanks it saves my day! – bdalina Dec 16 '19 at 3:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.