0

I'm using this code to add the alt text to my featured images on upload.

$image_title = get_post( $post->ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );
// Set the image Alt-Text
add_post_meta( $post->ID, '_wp_attachment_image_alt', $image_title );

It's working and I can see it on it's database table wp_postmeta under it's post ID.

Altough it's correctly registred on the database, the featured image doesn't have the Alt text (see the image bellow)

missing Alt Text

What could be the problem?

0

I believe you need to use set_post_thumbnail to actually set featured image:

set_post_thumbnail($_POST['post_id'], $attachment_id);
  • Sorry, that piece of code is in my original one and now is also on my example. Even though, it doesn't woks... – bpy Oct 30 '19 at 15:55
0

It's needed to pass the image ID from the media_handle_upload like this:

First we get the new image ID

$attach_id = media_handle_upload( $file_handler, $_POST['post_id'] );

Than we prepare the content of that alt="text":

// Prepare the alt="title"
$image_title = get_post( $post->ID )->post_title;
// Sanitize the title:  remove hyphens, underscores & extra spaces:
$image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ',  $image_title );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$image_title = ucwords( strtolower( $image_title ) );

And finaly we set the new image alt="text":

add_post_meta( $attach_id, '_wp_attachment_image_alt', $image_title );

The reason the code above was failing, was because the $post->ID is the ID of the post itself and not the attachment ID (wich is the one we need).

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.