Support » Developing with WordPress » Setting alt-text when attaching image

  • plufz

    (@plufz)


    Hi!

    I’m trying to insert an image attachment into the media gallery and insert it into the open post programmatically. I’m sort of half way there. The image is inserted into the gallery with an alt-text and inserted into the post but in the post it is missing the alt text.

    This is how I’m adding the image:

    $attachment_id   = wp_insert_attachment( $attachment, $image_file_path, $post_id );
    update_post_meta( $attachment_id, '_wp_attachment_image_alt', $my_alt_text);

    I’m guessing the problem is that I’m changing the alt text after the image is inserted into the post and that I somehow should pass the alt text to wp_insert_attachment() instead. But I can’t figure out how. Neither of these methods work:

    $attachment["alt"] = "...";
    $attachment["_wp_attachment_image_alt"] = "...";
    $attachment_id   = wp_insert_attachment( $attachment, $image_file_path, $post_id );
    • This topic was modified 1 month ago by bcworkz. Reason: code format fixed
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Directly setting alt text as post meta is fine, but if you’re changing it when inserting the image into post content, what the meta value here is is moot. How are you inserting img tags into post content? You should be able to specify the desired alt text then. For example, you could use wp_get_attachment_image() and pass the desired alt text as the “alt” element in the passed $attr array.
    https://developer.wordpress.org/reference/functions/wp_get_attachment_image/

    Rather nit-picky since I understand your meaning, but you may confuse others in referring to the back end media UI as the “gallery”. In WP docs it’s referred to as the “media library”. In WP lingo, “gallery” generally refers to front end elements that display multiple images as a group.

    Hi there,

    I’ve done something similar a while ago. The correct approach would be having a different action deal with attachment meta using add_attachment hook.

    Worths mentioning that I found this issue about using _wp_attachment_image_alt meta. https://github.com/WordPress/gutenberg/issues/12913

    Here is a gist I had for this example (it updates the alt tag from image name).

    I hope this helps.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.