1

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:

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); 
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);
  • Thank you! But... What i don't understand is how - id="attachments-'.$post->ID.'-foo" - is the same as - update_post_meta($post['ID'], 'foo', $attachment['foo']) – Ole Henrik Skogstrøm Mar 23 '12 at 22:43
  • And how do i call this metadata at the front end, to f.eks. check if the checkbox is checked (check check :p) – Ole Henrik Skogstrøm Mar 23 '12 at 22:47
  • it's not, but the name of the field is the same. to get the data you use get_post_meta($attachment_id,'foo',true); – Bainternet Mar 23 '12 at 23:31

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.