tr_a

This function makes it easier to work with links.

{* $link_arr - type: array, required *}
{* $optional_classes - type: string, optional, default: "" *}
{* $attrs_only - type boolean, optional, default: false *}

{tr_a(
  $link_arr,
  $optional_classes,
  $attrs_only
)}

Arguments

  1. $link_arr – required; Data for the link HTML generation.
  2. $optional_classes – optional; Adds the desired class name/s.
  3. $attrs_only – optional; If true, it will only print the attributes, instead of the whole <a> tag. See the example below:

<a> Tag Example

{var $link = [
  'title' => 'Click Here',
  'url' => 'https://webredone.com/theme-redone/',
  'target' => true
]}

{tr_a($link, 'btn btn--brand')}

Generates the HTML snippet below

<a 
  href="https://webredone.com/theme-redone/"
  target="_blank"
  rel="noopener noreferrer"
  class="btn btn--brand"
>
  Click Here
</a>

Attributes-Only Example

{var $link = [
  'url' => 'https://webredone.com/theme-redone/',
  'target' => false
]}

<a {tr_a($link, "", true)|noescape}>
  <img src="./image-src.jpg" />
</a>

Generates the HTML snippet below

<a 
  href="https://webredone.com/theme-redone/"
  target="_blank"
  rel="noopener noreferrer"
>
  Click Here
</a>

The $link array shows the structure we need for the function to work. We wouldn’t actually write the array ourselves because ACF’s link field, and our Gutenberg CTA component both return data in this format.


Why This Function?

We all know that the <a> tag is one of the most frequently used HTML elements on websites.

Also, we the developers, know that we should, most of the time, if not always, use if statements, and conditionally render fields on the front-end only when the admin had provided all the necessary data needed for the particular field.

This way, we make sure we avoid errors if the field is optional by design, or the admin had forgotten to populate it.

This, being a repetitive task, and us having to write conditionals each time we wanted to render a link, led us to create this helper function that does all those checks for us behind the curtains. This helps us write cleaner, error-free code, and do it faster.

Join Our Newsletter

To get updates about Theme Redone