tr_get_media

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

{tr_get_media('source.unsplash.com/500x500')}
{* Will render an image from a third-party website. *}
{tr_get_media('image1.png')} 
{* Will render [theme-root]/assets/img/image1.png located in theme assets. *}
{tr_get_media('people/image1.jpg')}
{* Will render [theme-root]/assets/img/people/image1.png located in theme assets.*} 
{tr_get_media('http://localhost/theme_redone/wp-content/uploads/2022/05/African-savanna-elephant.jpg')}
{* 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

{tr_get_media([
  'src' => 'source.unsplash.com/500x500',
  '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:

<div 
  class="tr-img-wrap-outer" 
  style="--size-w-original:500;--size-h-original: 333;"
>
  <div class="tr-img-wrap">
    <img 
      class="js-img-lazy" 
      src="" 
      data-img-src="[path-to-the-image.format]" 
      alt="[alt text if provided]"
    />
  </div>
</div>

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