Add "alt" tag to images wordpress

357 Views Asked by At

I'm trying to solve a situation by creating a code that checks and automatically adds alt tag from the name. It works partially, that is, it does what it has to do, but whatever I do, I end up consuming resources, in one way or another. Can someone please lend a hand? I think it is useful to many. It is very helpful when you have many images, in my case 40 k

// Set the number of images to process per batch
$batch_size = 2;

// Set the page number to start from
$page_number = 1;

// Set a flag to indicate if there are more images to process
$more_images = true;

// Loop through each batch of images
while ($more_images) {
// Get the current batch of images
$images = get_posts([
"post_type" => "attachment",
"post_mime_type" => "image",
"posts_per_page" => $batch_size,
"orderby" => "ID",
"order" => "DESC",
"paged" => $page_number,
]);
// Check if there are any images in the batch
if (!empty($images)) {
// Initialize an array to store the image IDs and alt tags
$image_data = [];
  // Loop through each image in the batch
  foreach ($images as $image) {
       // Get the image ID
       $post_ID = $image->ID;

       // Check if the image has an empty alt tag
       $alt = get_post_meta($post_ID, "_wp_attachment_image_alt", true);
       if (empty($alt)) {
            // Get the image title
            $my_image_title = get_post($post_ID)->post_title;

            // Sanitize the title: remove hyphens, underscores & extra spaces
            $my_image_title = preg_replace(
                 "%\s*[-_\s]+\s*%",
                 " ",
                 $my_image_title
            );

            // Sanitize the title: capitalize first letter of every word (other letters lower case):
            $my_image_title = ucwords(strtolower($my_image_title));

            // Store the image ID and sanitized title in the image data array
            $image_data[$post_ID] = $my_image_title;
       }

       // Add a 2-second work break between two images
       sleep(2);
  }

  // Update the alt tags for all images in the batch
  foreach ($image_data as $post_ID => $alt_tag) {
       update_post_meta(
            $post_ID,
            "_wp_attachment_image_alt",
            $alt_tag
       );
  }

  // Increment the page number
  $page_number++;
} else {
// Set the flag to indicate that there are no more images to process
$more_images = false;
}

// Pause for a few seconds before moving on to the next batch
sleep(5);
}
0

There are 0 best solutions below