tr_get_media is a helper function that makes it easier to render images and SVGs synchronously or asynchronously.

It accepts two arguments:

tr_get_media($media, $async)

  • $media can be either a path string to the image/SVG or an associative array containing “src” and “alt” (alt is optional) properties.
  • $async – Boolean. Default is false and when omitted renders the image synchronously. When set to true, it renders it asynchronously.

Passing a string as the first argument

{* Will render an image from a third-party website. *}
{* Will render [theme-root]/assets/img/image1.png located in theme assets. *}
{* Will render [theme-root]/assets/img/people/image1.png located in theme assets.*} 
{* Will render the image from the media uploads directory. *}

If any of the paths above would be replaced with a path to the SVG file, the function would then copy the contents of that SVG file and paste them in HTML where the function is called

If we add a second argument (true) to the function, the image/SVG would load asynchronously after the DOMContentLoaded

Passing an associative array as the first argument

  'src' => '',
  'alt' => 'This is alt text'
{* Will render an image from a third-party website with the alt attribute. *}

The associative array format would work for all the examples above (SVGs, obviously, would not have an alt attribute).

When images are loaded asynchronously, we will get this snippet of HTML:

  style="--size-w-original:500;--size-h-original: 333;"
  <div class="tr-img-wrap">
      alt="[alt text if provided]"

The JS will swap the src with a path from the “data-img-src” attribute.

We are also getting the image dimensions on the backend and passing them as CSS variables in order to prevent CLS (content jumping).

We have used the height: 0; padding-bottom: [height-in-percents]% hack here to preserve the aspect ratio of the image (Similar to how Next.js handles async loading of images).

Join Our Newsletter

To get updates about Theme Redone