Set ALT Word Limit When You Use Plugin for Thumbnail

Hey! If you have use any plugins for automatic thumbnail, And you want to set word limit for ALT text. So you can use given code on your website’s theme and set automatically ALT text limit.

How to Do

  • Open your website’s theme.
  • Then open functions.php file and Paste given code.
// Automatic image ALT name
function auto_image_alt_name_thekroyaard( $post_ID ) {
if ( wp_attachment_is_image( $post_ID ) ) {
$auto_alt_image_title = get_post( $post_ID )->post_title;
$new_alt_name = wp_trim_words( $auto_alt_image_title, 6, $more = ' Thumbnail' );
update_post_meta( $post_ID, '_wp_attachment_image_alt', $new_alt_name );
}
}
add_action( 'add_attachment', 'auto_image_alt_name_thekroyaard' );
  • Then SAVE.

Additional code

If want to add post id after post title name on ALT name so add simple code or add one line in given code –

// Automatic image ALT name
function auto_image_alt_name_thekroyaard( $post_ID ) {
if ( wp_attachment_is_image( $post_ID ) ) {
$auto_alt_image_title = get_post( $post_ID )->post_title;
$auto_alt_image_id = get_the_ID();
$new_alt_name = wp_trim_words( $auto_alt_image_title, 6, $more = __( ' '. $auto_alt_image_id . ' Thumbnail') );
update_post_meta( $post_ID, '_wp_attachment_image_alt', $new_alt_name );
}
}
add_action( 'add_attachment', 'auto_image_alt_name_thekroyaard' );

Remove Dash or make SEO friendly

// Automatic image ALT name
function auto_image_alt_name_thekroyaard( $post_ID ) {
if ( wp_attachment_is_image( $post_ID ) ) {
$auto_alt_title = get_post( $post_ID )->post_title;
$auto_alt_id = get_the_ID();
$new_alt_name = wp_trim_words( $auto_alt_title, 5, $more = __( ' '.' Thumbnail '. $auto_alt_id ) );
$new_alt_name = str_replace(array(' ', '–', ',', '|' ,'.'), '-', $new_alt_name);
$new_alt_name = preg_replace('/[^A-Za-z0-9\-]/', '', $new_alt_name);
$new_alt_name = preg_replace('/-+/', '-', $new_alt_name);
update_post_meta( $post_ID, '_wp_attachment_image_alt', $new_alt_name );
}
}
add_action( 'add_attachment', 'auto_image_alt_name_thekroyaard' );

Hope this code worked on your Theme. Thanks for visting.