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:
-
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...
-
How to Remove the "Website" Field from the WordPress Comment Form
By default, WordPress includes a "Website" or "URL" field in its comment form. While this may be useful in some cases, it often attracts spammers who leave low-quality co...
-
Step Options Plugin for WordPress
At some point, I needed a way to display identical content blocks across multiple pages, with the ability to manage and update them easily from the WordPress admin panel....
Leave a Reply