Fixing Image URL in ACF (Advanced Custom Fields)
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" />';
}
Similar posts:
-
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...
-
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...
-
How to Remove the jQuery Migrate Script from WordPress
If your WordPress project uses jQuery, then by default, WordPress also loads the jQuery Migrate script along with it. In 99% of cases, you don’t actually need this script...
Leave a Reply