2

I'm using WP 4.1.1 and trying to create a default value for the 'Alt text' when uploading an image (dropping it straight into post and dialog appears).

I've tried doing this with this hook https://codex.wordpress.org/Plugin_API/Filter_Reference/attachment_fields_to_edit

and while I seem to be able to ADD a new field (it appears on the dialog form), I cannot modify the value of the 'Alt Text' field. So the following does NOT work (but should, according to the docs!). I have tried changing the priority from high to very low too, no difference.

add_filter('attachment_fields_to_edit', 'dpcontent_attachment_fields_to_edit', 999, 2 );

function dpcontent_attachment_fields_to_edit($form_fields, $post) {

    if ( substr( $post->post_mime_type, 0, 5 ) == 'image' ) {        
        _log("DBG: 1 in here ... form_fields=" . arr_to_string($form_fields)); // its empty :-(

        $form_fields['image_alt'] = array(
            'value' => 'Hello world!',
            'label' => __('Alternative Text'),
            'show_in_model' => true
        );
    }

    return $form_fields;
}

Any help with this would be greatly appreciated!

gvanto

  • What about the attachment_fields_to_save filter? There is an example for setting a default caption if the user doesn't fill in anything and might also work for alt text. – Gabriel Mar 24 '15 at 11:48
  • Nope, doesn't work. I think that filter is for when saving the attachment (AFTER it is inserted into the post maybe? the documentation on CODEX wasn't very clear to me). I actually found that wp_generate_attachment_metadata filter works OK, even though it doesn't exactly do what I want its an OK workaround – gvanto Mar 24 '15 at 21:59
3

Ok, the answer will not be short

At first, You can't change the alt attribute using attachment_fields_to_edit, because you can't modify default fields. To see how this works can be in the source code of get_compat_media_markup.

With attachment_fields_to_edit you can add only additional input fields.

Example:

/**
 * Add custom field for Images
 *
 * @param array   $fields An array of attachment form fields.
 *                field arguments:
 *                    array(
 *                      'show_in_edit'  => (bool)  Show in Edit Screen. Default true,
 *                      'show_in_modal' => (bool)  Show in Modal Screen. Default true,
 *                      'label'         => string  label text,
 *                      'input'         => string  input type: text, textarea, etc or 'html' key with custom input html callback. Default 'text'
 *                      'required'      => (bool)  Input attributte 'required'. Default false,
 *                      'html'          => string  custom input html or callback name,
 *                      'extra_rows'    => array(),
 *                      'helps'         => string  help text,
 *                    )
 * @param WP_Post $post        The WP_Post attachment object.
 */
function add_attachment_fields($fields, $post)
{
  if (substr($post->post_mime_type, 0, 5) == 'image') {
    $meta = wp_get_attachment_metadata($post->ID);
    $fields['meta_credit'] = array(
      'label'       => __('Credit'),
      'input'       => 'text',
      'value'       => $meta['image_meta']['credit'],
      'helps'       => __('Only text. Max length 40 characters'),
      'error_text'  => __('Error credit meta')
    );
  } 
  return $fields;
}
add_filter('attachment_fields_to_edit', 'add_attachment_fields', 10, 2);

For save value, use attachment_fields_to_save:

/**
 * Filters the attachment fields to be saved.
 * @param array $post       An array of post data.
 * @param array $attachment An array of attachment metadata.
 */
function update_attachment_fields($post, $attachment)
{
  if (isset($attachment['meta_credit'])) {
    $credit = $attachment['meta_credit'];
    $meta = wp_get_attachment_metadata($post['ID']);
    if ($credit !== $meta['image_meta']['credit']) {
        $meta['image_meta']['credit'] = $credit;
        wp_update_attachment_metadata($post['ID'], $meta);
    }
  }
  return $post;
}
add_filter('attachment_fields_to_save', 'update_attachment_fields', 10, 2);

What to do with the alt attribute? No good idea, although it is not good to keep trash in database, but work:

add_attachment and add_post_meta variant fires once when attachment is added:

add_action('add_attachment', 'add_alt_to_attachment');
function add_alt_to_attachment($post_ID)
{
    add_post_meta($post_ID, '_wp_attachment_image_alt', 'MY TEXT');
}

Fired, when any field change:

function update_alt_field($post, $attachment)
{
  if (empty($attachment['image_alt'])) {
    $image_alt = wp_unslash('My Alt is good');
    $image_alt = wp_strip_all_tags($image_alt, true);
    // Update_meta expects slashed.
    update_post_meta($attachment_id, '_wp_attachment_image_alt', wp_slash( $image_alt));
  }
  return $post;
}
add_filter('attachment_fields_to_save', 'update_alt_field', 10, 2);

And other way - add alt text when image inserting in post:

/**
 * Filter the list of attachment image attributes.
 *
 * @param array            $attrs        Attributes for the image markup.
 * @param WP_Post        $attachment    Image attachment post.
 * @param string|array    $size        Requested size. Image size or array of width and height values
 *                                 (in that order). Default 'thumbnail'.
 * @return array        $attrs        Attributes for the image markup.
 */
function my_images_attr($attrs, $attachment, $size)
{
    if (empty($attrs['alt'])) {
        $attrs['alt']) = 'MY TEXT';
    }
    return $attrs;
}
add_filter('wp_get_attachment_image_attributes', 'my_images_attr', 10, 3);
1

I found a solution to add a default caption for all new uploaded attachments:

function add_caption_to_attachment($data, $postarr){
  if(empty(trim($data['post_excerpt']))){
    $data['post_excerpt'] = '«<a href="">TITEL</a>» - <a href="">NAME</a>, CC <a href="">XXX</a>';
  }
  return $data;
}
add_filter('wp_insert_attachment_data', 'add_caption_to_attachment');

The solutions proposed by @vralle work well for actual attachment meta data, but caption is not. So I had to find another way, add_attachment hook did not work.

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.