Attachment Meta Data Not Saving When Using Radio Buttons

I have created the following meta data options for my image attachments. Basically, the user selects a radio button – the appropriate class is then added to a div, which is wrapped around the attachment. For some reason, the selected radio button value isn’t being saved. However, I have noticed that if I switch the input to be a regular text field, everything works perfectly fine.

function add_attachment_classes_field( $form_fields, $post ) {
$field_value = get_post_meta( $post->ID, 'classes', true );
  $form_fields['classes'] = array(
    'value' => $field_value ? $field_value : '',
    'label' => __( 'Classes' ),
    'input' => 'html',
    'html' => "<div><input checked='checked' style='width: initial' type='radio' name='border-style' value=''> None</div>
                <div><input style='width: initial' type='radio' name='border-style' value='green-border'> Green</div>
                <div><input style='width: initial' type='radio' name='border-style' value='red-border'> Red</div>
                <div><input style='width: initial' type='radio' name='border-style' value='jagged-border'> Jagged</div>
                <div><input style='width: initial' type='radio' name='border-style' value='purple-border'> Purple</div>",
  );  
 return $form_fields;
}

function save_attachment_classes( $attachment_id ) {
  if ( isset( $_REQUEST['attachments'][$attachment_id]['classes'] ) ) {
    $classes = $_REQUEST['attachments'][$attachment_id]['classes'];
    update_post_meta( $attachment_id, 'classes', $classes );
  }
}

function wrap_my_div($html, $id, $caption, $title, $align, $url, $size, $alt) {
    $field_value = get_post_meta( $id, 'classes', true );
    return '<div class="'.$field_value.'">'.$html.'</div>';
}
add_action( 'edit_attachment', 'save_attachment_classes' );
add_filter( 'attachment_fields_to_edit', 'add_attachment_classes_field', 10, 2 );
add_filter( 'image_send_to_editor', 'wrap_my_div', 10, 8 );

Related posts

Leave a Reply

1 comment

  1. The issue seems to be with the name attribute for the radio button.

    I changed each one to the following and it solved the problem:

    name='attachments[{$post->ID}][classes]'