php - Retrieve alt text by referencing img src - Wordpress

one text

I have a website with 400+ images. Using a spreadsheet plugin I've been through and manually added alt text to each of the images.

The problem I have is that the pages are built with a page builder and a lot of the images where added in text blocks using <img src="https://example.com/image-folder/image-name.jpg"> and therefore haven't dynamically pulled in the alt text.

I'm trying to avoid having to go through all of the pages, find the img code, work out which image it is, look up the alt text and manually type it, again!

I'm thinking there must be a way to reference the image in the database by the img src, then get the alt text from the database that way.

I'd like to write a function that sits in the functions file and I can call from the alt text. Something like this get_alt_text():

<img src="https://example.com/image-folder/image-name.jpg" alt="<?php echo( get_alt_text() ); ?>">

This way I can just paste in a single bit of text into each image alt which would save a ton of time.

It seems there are functions that could help me, but it's a bit more than I fully understand right now and wondered if someone could at least say (with confidence) that it's possible or not.

For example this Wordpress "attachment_url_to_postid" function.

or this "wp_get_attachment_image_src" function

My thinking for the function is:

  • Get the img src
  • match that to an image in the database
  • get that image ID and meta data etc
  • separate the alt text and pass that back

So, my question is:

  • Can you tell me if this is possible?
  • Even better, point me in the right direction.
  • Even better yet! Show an example.

Thank you for your time.

Source