wordpress

Fixing Image URL in ACF (Advanced Custom Fields)

Last updated: 23.02.2026
Views: 395

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:

  • Caching Data to a File Using PHP
    Sometimes it becomes necessary to limit the number of requests to an external data source, especially when the data does not change frequently. For example, this can be u...
  • Joomla Google Maps Module
    StepMap is a free Google maps module for Joomla. This module is designed for Joomla 6. However, it also works on Joomla 5. The module was not tested on low versions of th...
  • Classic WordPress widget (plugin) of NBU exchange rates (Ukraine)
    WP Currency NBU - classic NBU (National Bank of Ukraine) exchange rate widget for WordPress. The widget displays the USD (US Dollar), EUR (Euro), PLN (Polish Zloty) excha...

Leave a Reply

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