Add select field to media uploader that adds a class to the image

I’m looking for a way to add a <select> menu to the media uploader that will have two options: normal image, which will do nothing, and profile image, which will add a CSS class to the image if it is selected.

I have gotten as far as adding the select menu to the uploader, but I don’t know how to:

Read More
  • apply a class to the image based on the selected option
  • make sure the selected option stays selected
  • make sure the selected option can be changed later

This is what I have so far:

function my_profile_image_select( $form_fields, $post ) {
    $form_fields['image-type'] = array(
        'label' => 'Image Type',
        'input' => 'html',
        'helps' => 'Enter "profile-image" to enable profile image caption',
    );

    $profile_image = 'profile-image';
    $normal_image = 'normal-image';
    $form_fields['image-type']['html'] = '<select name="Profile Image Select" id="Profile Image Select">';
    $form_fields['image-type']['html'] .= '<option value="' . $normal_image . '">Normal Image</option>';
    $form_fields['image-type']['html'] .= '<option value="' . $profile_image . '">Profile Image</option>';
    $form_fields['image-type']['html'] .= '</select>';

   return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'my_profile_image_select', 10, 2 );

Related posts

1 comment

  1. To apply the class you need a custom function to do something with the value of your setting.

    To make sure the selected stays selected use the WP selected() function

        $form_fields['image-type']['html'] = "<select name='attachments[{$post->ID}][profile_image_select]'>";
        $form_fields['image-type']['html'] .= '<option '.selected(get_post_meta($post->ID, "_profile_image_select", true), 'default',false).' value="' . $normal_image . '">Normal Image</option>';
        $form_fields['image-type']['html'] .= '<option '.selected(get_post_meta($post->ID, "_profile_image_select", true), 'default',false).' value="' . $profile_image . '">Profile Image</option>';
        $form_fields['image-type']['html'] .= '</select>';
    

Comments are closed.