Adding a custom toolboxtwig shortcode

Code

January 21, 2020

Sometimes you just need a custom field’s value in a regular module, or even in a Gutenberg layout. Creating a shortcode in such circumstances would be a way to solve this quickly.

Toolbox allows you to use Twig Templates to solve many of such problems quickly. You can add and update a Twig Template from your dashboard, add as many attributes as you need and use those to render your output.

Sidenote:

Twig is a render engine, meaning that it is mostly useful for outputting HTML. You can enqueue scripts and styles more easily when you create a shortcode through PHP.

Enabling toolboxtwig shortcode

Assuming you have already installed the Timber Library plugin and turned on Twig Templates CPT, you also need to make sure that you have ticked the “Enable toolboxtwig shortcode” in the Toolbox Settings. It is deactivated by default.

Creating the Twig Template that outputs an ACF Link field

The ACF Link field is a field that stores a link text, url and target for a link. It can be used to create both internal and external links using just one field.

To output that field using your own styling you can add the following Twig Template and go from there:

{# get the fieldname defined in the shortcodes attributes from the post, store it as variable 'field' #}
{% set field = attribute( post, __atts__.field ) %}
<a href="{{ field.url}}" target="{{field.target}}">{{ field.title }}</a>

Make sure to check the exact slug/post_name that is created for your Twig Template.

In your layout or Gutenberg Block, you can now add the shortcode:

[toolboxtwig field="acf_fieldname" twigtemplate="twig_template_slug"]

Beaverplugins

Web ninja with PHP/CSS/JS and Wordpress skills. Also stand-in server administrator, father of four kids and husband to a beautiful wife.
Always spends too much time figuring out ways to do simple things even quicker. So that you can benefit.