Skip to content

Instantly share code, notes, and snippets.

@plugin-republic
Created April 29, 2024 08:43
Show Gist options
  • Save plugin-republic/c13df04112a1c2e1962a82b7f6dc5b78 to your computer and use it in GitHub Desktop.
Save plugin-republic/c13df04112a1c2e1962a82b7f6dc5b78 to your computer and use it in GitHub Desktop.
Query WordPress attachments with no alt text and automatically create alt text using file name
<?php
/**
* Query WordPress attachments with no alt text
* Automatically create alt text using file name
* Remove this snippet once you've run it
*/
function pr_query_attachments() {
if( did_action( 'init' ) > 1 ) {
return;
}
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10, // You can increase this number here if you wish
'meta_key' => '_wp_attachment_image_alt',
'meta_compare' => 'NOT EXISTS'
);
$attachments = get_posts($args);
if ($attachments) {
foreach( $attachments as $post) {
setup_postdata($post);
error_log( $post->ID ); // This is the attachment ID
$alt = get_post_meta( $post->ID, '_wp_attachment_image_alt', true );
$name = $post->post_name;
if( ! $alt ) {
$alt = str_replace( array( '-', '_' ), ' ', $name ); // Replace dashes and underscores with spaces
$alt = preg_replace('/\d/', '', $alt ); // Remove numbers
$alt = trim( $alt ); // Remove white space
$alt = ucfirst( $alt ); // Caps first letter
if( $alt ) {
update_post_meta( $post->ID, '_wp_attachment_image_alt', $alt );
error_log( $alt ); // Just print the new alt tag - you can comment this line out
}
}
}
}
}
add_action( 'init', 'pr_query_attachments' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment