Last active
August 6, 2019 07:04
-
-
Save linkdigitaluk/f951c2d81e626b73bb75f7ae26eb77b3 to your computer and use it in GitHub Desktop.
[Autopopulate image data (WP)] Autopopulate the Alt, Title and Description fields, using the image name, when uploading an image through WordPress #WordPress #A11y
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Set alt, title and description for image uploads */ | |
function set_image_meta_upload( $post_ID ) { | |
if ( wp_attachment_is_image( $post_ID ) ) { | |
$my_image_title = get_post( $post_ID )->post_title; | |
$my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', | |
$my_image_title ); | |
$my_image_title = ucwords( strtolower( $my_image_title ) ); | |
$my_image_meta = array( | |
'ID' => $post_ID, | |
'post_title' => $my_image_title, | |
'post_content' => $my_image_title, | |
); | |
// Set the image Alt-Text | |
update_post_meta( $post_ID, '_wp_attachment_image_alt', | |
$my_image_title ); | |
// Set the image meta (e.g. Title, Excerpt, Content) | |
wp_update_post( $my_image_meta ); | |
} | |
} | |
add_action( 'add_attachment', 'set_image_meta_upload' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment