Custom classes for attachments

I'm trying to create a custom field in ATTACHMENT DETAILS section. I want to add in this field multiply words separated by space which will be than added as a classes to particular images.

This is the solution I've found so far. It adds custom field but it doesn't add a class to images. What is wrong here?

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' ),
    'helps' = __( 'Add class seperated by space' )
  );
 return $form_fields;
}
add_filter( 'attachment_fields_to_edit', 'add_attachment_classes_field', 10, 2 );

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 );
  }
}
add_action( 'edit_attachment', 'save_attachment_classes' );

Topic attachment-fields-to-edit custom-field Wordpress

Category Web


Just add the following code in functions.php file of your theme which will add your custom added classes to images when you will insert it into post editor.

function add_image_class($html, $id, $caption, $title, $align, $url, $size, $alt = '' ){
$classes = get_post_meta( $id, 'classes', true );
if ( preg_match('/<img.*? class=".*?">/', $html) ) {
    $html = preg_replace('/(<img.*? class=".*?)(".*?>)/', '$1 ' . $classes . '$2', $html);
} else {
    $html = preg_replace('/(<img.*?)>/', '$1 class="' . $classes . '" >', $html);
}
return $html;
}
add_filter('image_send_to_editor','add_image_class',10,8);

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.