Skip to content

Instantly share code, notes, and snippets.

@sagive
Last active May 10, 2022 10:25
Show Gist options
  • Save sagive/75551b8205e7a4cd020ec1d2ff6710e5 to your computer and use it in GitHub Desktop.
Save sagive/75551b8205e7a4cd020ec1d2ff6710e5 to your computer and use it in GitHub Desktop.
Wordpress image alt tag fixed based on image file name / title
<?php
/********************************************************
** IMAGE ALT, GLOBAL FIX
** run trough all existing images, grab the image title
** which is built using the filename automaticlly and
** asign it to the alt - at-least it wont be empty!
********************************************************/
add_action('after_setup_theme', 'image_alt_fix');
function image_alt_fix() {
$args = array(
'post_type' => 'attachment',
'post_mime_type' => 'image/jpeg,image/gif,image/jpg,image/png',
'post_status' => 'all',
'posts_per_page' => -1,
);
$imgs = new WP_Query( $args );
if( $imgs->have_posts() ) {
while( $imgs->have_posts() ) {
$imgs->the_post();
$tid = get_the_ID();
$ttitle = get_the_title();
$alt = get_post_meta($tid, '_wp_attachment_image_alt', true);
if( empty($alt) ) {
// testing:
// echo 'MISSED ALT TAG:'.get_the_title($tid).'<br>';
update_post_meta(get_the_ID(), '_wp_attachment_image_alt', get_the_title());
}
}
}
}
/********************************************************
** ON UPLOAD SET MINIMAL ALT TAG IN IMAGES
********************************************************/
add_action( 'add_attachment', 'sagive_automate_imgalt' );
function sagive_automate_imgalt( $img_id ) {
// is this an image?
if ( wp_attachment_is_image( $img_id ) ) {
$imgTitle = get_post( $img_id )->post_title;
$imgTitle = preg_replace( '%\s*[-_\s]+\s*%', ' ', $imgTitle ); // Removes hyphens, underscores etc
$imgTitle = ucwords( strtolower( $imgTitle ) ); // Capitaliztion etc
// reset image title using formatted title
$imgMeta = array(
'ID' => $img_id,
'post_title' => $imgTitle,
);
wp_update_post( $imgMeta );
update_post_meta( $img_id, '_wp_attachment_image_alt', $imgTitle ); // Set the alt text
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment