wordpress

Fixing Image URL in ACF (Advanced Custom Fields)

Last updated: 23.02.2026
Views: 379

The ACF (Advanced Custom Fields) plugin is a great and convenient tool for extending the functionality of WordPress. ACF allows you to add custom fields to your project’s admin panel. When using the image field, I usually use the URL to get the value.

And in the template, when outputting the image field value, the correct value does not always come. Sometimes, instead of the URL, an ID comes. This usually happens in a loop when you are outputting elements from an array. You can fix this behavior with the following code:

PHP

$logo = get_field('logo');
if (is_numeric($logo)) {
    $logo_url = wp_get_attachment_url($logo);
} else {
    $logo_url = $logo; // string (URL)
}

If image fields are used in different templates, it makes sense to move this fix to the functions.php file.

PHP

// functions.php

function getAcfImgUrl($img){
    if (is_numeric($img)) {
        return wp_get_attachment_url($img);
    } 
    return $img;
}

In the template, this might look like the one shown below. But it all depends on your implementation, and you will have your own field names.

PHP

$offers = get_field('offer_list');
foreach ($offers as $item) { 
   $icon = getAcfImgUrl($item['icon']);
      
   // other code...

  echo '<img src="' . $icon . '" atl="icon" />'; 
}
author
Author: Igor Rybalko
I have been working as a front-end developer since 2014. My main technology stack is Vue.js and WordPress.

Similar posts:

Leave a Reply

Your email address will not be published. Required fields are marked *