Created
April 29, 2024 08:43
-
-
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
This file contains hidden or 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
<?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