The snippet below makes sure that every image you upload to a WordPress post or page gets set to “full size” by default. It also takes the file name and creates the image “alt” text automatically based on it.
Optionally, you can capitalize each word of the alt text and set the caption of the image, too.
Add the snippet either to your theme’s functions.php file, or to your favorite code snippets plugin.
// Set the alt text and title of an image based on the file name
function auto_set_image_meta_on_upload( $post_ID ) {
// Check if the uploaded file is an image
if ( wp_attachment_is_image( $post_ID ) ) {
// Get the full file path
$file_path = get_attached_file( $post_ID );
// Extract the file name without its extension
$file_name = pathinfo( $file_path, PATHINFO_FILENAME );
// Format the file name: replace dashes/underscores with spaces and capitalize words
$formatted_name = str_replace( array('-', '_'), ' ', $file_name );
// Capitalize words?
//$formatted_name = ucwords( $formatted_name );
// Sanitize the formatted name
$formatted_name = sanitize_text_field( $formatted_name );
// Update the attachment post
$attachment_data = array(
'ID' => $post_ID,
'post_title' => $formatted_name,
//'post_excerpt' => $formatted_name, // Leave active if you also want to set post captions automatically
);
wp_update_post( $attachment_data );
// Set the alt text
update_post_meta( $post_ID, '_wp_attachment_image_alt', $formatted_name );
}
}
add_action( 'add_attachment', 'auto_set_image_meta_on_upload' );
// Image size to full on upload
update_option( 'image_default_size', 'full' );
