Based on the article here https://www.damiencarbery.com/2018/07/set-image-alt-field-on-upload-and-on-use/ I have the following code:
function dcwd_title_to_words( $title ) {
// Sanitize the title: remove hyphens, underscores & extra spaces:
$title = preg_replace( '%s*[-_s]+s*%', ' ', $title );
// Sanitize the title: capitalize first letter of every word (other letters lower case):
$title = ucwords( strtolower( $title ) );
return $title;
}
add_action( 'add_attachment', 'dcwd_set_image_meta_upon_image_upload' );
function dcwd_set_image_meta_upon_image_upload( $post_ID ) {
if ( wp_attachment_is_image( $post_ID ) ) {
$parent_id = wp_get_post_parent_id( $post_ID ); // Get the parent post ID
$parent_title = get_the_title( $parent_id ); // Get the title of the parent post
$parent_title = dcwd_title_to_words( $parent_title ); // Sanitize the title
$my_image_title = $parent_title;
$my_image_meta = array(
'ID' => $post_ID,
'post_title' => $my_image_title,
'post_content' => $my_image_title,
);
update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
wp_update_post( $my_image_meta );
}
}
add_filter('image_send_to_editor', 'dcwd_auto_alt_fix_1', 10, 2);
function dcwd_auto_alt_fix_1($html, $id) {
$parent_id = wp_get_post_parent_id( $id );
$parent_title = get_the_title( $parent_id );
$parent_title = dcwd_title_to_words( $parent_title );
return str_replace('alt=""','alt="' . $parent_title . '"',$html);
}
add_filter('wp_get_attachment_image_attributes', 'dcwd_auto_alt_fix_2', 10, 2);
function dcwd_auto_alt_fix_2($attributes, $attachment){
if ( !isset( $attributes['alt'] ) || '' === $attributes['alt'] ) {
$parent_id = wp_get_post_parent_id( $attachment->ID );
$parent_title = get_the_title( $parent_id );
$parent_title = dcwd_title_to_words( $parent_title );
$attributes['alt'] = $parent_title;
}
return $attributes;
}
add_filter( 'post_thumbnail_html', 'meks_post_thumbnail_alt_change', 10, 5 );
function meks_post_thumbnail_alt_change( $html, $post_id, $post_thumbnail_id, $size, $attr ) {
$parent_title = get_the_title( $post_id );
$html = preg_replace( '/(alt=")(.*?)(")/i', '$1'.esc_attr( $parent_title ).'$3', $html );
return $html;
}
The code adds the title of the article to the title, alternative title and description of the image. Everything works perfectly if I have activated the classic editor (with the “Classic editor” plugin). If I use Gutenberg, instead of the title of the article, write “automatic draft” in all fields of the image. In Gutenberg, it adds the title of the article only if I save the article before loading the image, it does not add it without saving it first. Can you help me make it functional with Gutenberg as well?
Thank you in advance!