Twig get_attachment() returns "Call to undefined function" despite WordPress Extension being enabled

Hi all,

I’m trying to use the Twig WordPress Extension function get_attachment() to retrieve an attachment URL from a media library item by ID, but I’m getting an error indicating the function is undefined — even though the WordPress Extension is enabled in Theme Options.

I’m on the latest version of Pro, Twig enables, and have the following Twig Extensions enabled: WordPress, HTML Extra, Advanced, Cache, Debug

The test case

I placed the following code in a regular Text element to isolate the issue:

{{ get_attachment(28261).src }}

Where 28261 is a valid attachment ID from the Media Library.

Result

Could not render Twig template:
An exception has been thrown during the rendering of a template 
("Call to undefined function get_attachment()") in 
"{{ get_attachment(28261).src }}" at line 1.

What I’ve already verified

  • {{ 1 + 1 }} works correctly, so Twig itself is functioning
  • Toggling the WordPress Extension off and on, saving each time, did not resolve it
  • {{ Attachment(28261).src }} → “Unknown ‘Attachment’ function”
  • {{ fn('wp_get_attachment_url', 28261) }} → “Unknown ‘fn’ function” (despite Advanced Extension being enabled)

It seems the WordPress and Advanced extensions are toggled on but their functions aren’t actually being registered.

Screenshots


Question

What’s the correct way to retrieve an attachment URL by ID in Twig within Pro? Is there an additional setup step I’m missing for these extensions to actually register their functions? Do you have a simple example that should be working and which could use to further debug this?

Thanks!

Hey @dhunink,

Thanks for posting in!

If get_attachment() and fn() won’t register, try the raw WordPress function approach within a custom Twig filter:

Since you have the Advanced Extension enabled (but fn() isn’t working), you may need to register a custom Twig function manually in your child theme’s functions.php :


// Add this to your child theme's functions.php
function twig_get_attachment_url($id) {
    return wp_get_attachment_url($id);
}

// Register as Twig function (adjust based on Pro's Twig setup)
add_filter('twig_environment', function($twig) {
    $twig->addFunction(new \Twig\TwigFunction('get_attachment_url', 'twig_get_attachment_url'));
    return $twig;
});

Then in Twig template:

{{ get_attachment_url(28261) }} 

Meanwhile, I will forward this to our developers for them to investigate the issue as well.

Best Regards.