How do i save and retrieve custom attachment meta?

I’m trying to save if a checkbox inside of the media uploader pop up is checked, so i can retrieve it from the front end.

I’m using this code:

Read More
function filter_attachment_fields_to_edit( $form_fields, $post ) {
    $foo = (bool) get_post_meta($post->ID, 'foo', true);

    $form_fields['foo'] = array(
        'label' => 'Is Foo',
        'input' => 'html',
        'html' => '<label for="attachments-'.$post->ID.'-foo"> ' . '<input type="checkbox" id="attachments-'.$post->ID.'-foo" name="attachments['.$post->ID.'][foo]" value="1"'.($foo ? ' checked="checked"' : '').' /> Yes</label>  ',
        'value' => $foo,
        'helps' => 'Check for yes'
    );
    return $form_fields;
}

from this question:
How to add a checkbox element to attachments editor with example

I have to admit i don’t completely understand how this piece of code is put together. I tried using this function to save:

function image_attachment_fields_to_save($post, $attachment) {  
    if( isset($attachment['imageLinksTo']) ){  
        update_post_meta($post['ID'], '_imageLinksTo', $attachment['imageLinksTo']);  
    }  
    return $post;  
} 

add_filter("attachment_fields_to_edit", "image_attachment_fields_to_edit", null, 2); 
add_filter("attachment_fields_to_save", "image_attachment_fields_to_save", null, 2); 

Related posts

Leave a Reply

1 comment

  1. The field id has to match in both function so if your field id is foo the when you save you need to look for that id and when you save a checkbox field its smart to remove it if not set so:

    function image_attachment_fields_to_save($post, $attachment) {  
        if( isset($attachment['foo']) ){  
            update_post_meta($post['ID'], 'foo', $attachment['foo']);  
        }else{
             delete_post_meta($post['ID'], 'foo' );
        }
        return $post;  
    }
    
    add_filter("attachment_fields_to_save", "image_attachment_fields_to_save", null, 2);