Parameters: return the URL source of an Image field

I have been exploring the use of components and parameters and have frequently now come across the need to access the URL source of an image / attachment field for use in links and other places.

With some tinkering I have been able to add a filter to a few different Dynamic Content fields to get the URL source if presented with the image id via a field. This is, in theory, also applicable in the case of returning an ACF image that is giving an ID as its return value.

The following code adds the ability to include a return="url" argument to the Dynamic Content insert:

function cx_supply_field_image( $result, $field, $args ) {

    // Only continue if the "return" argument is set, and is set to "url"
    if ( !isset( $args['return'] ) && $args['return'] != "url" )
        return $result;

    // Split the image ID:size
    $parts = explode(':', $result);
    $image_id = intval($parts[0]);

    // If the $image_id really is an integer, we can then grab the URL of the attachment
    if ($image_id) { 

        // default to "full" size if it didn't have a size in the field
        $size = isset($parts[1]) ? $parts[1] : 'full';

        $image_src = wp_get_attachment_image_src($image_id, $size);

        $result = $image_src[0];
    }

    return $result;
}
// Add the above filter to acf fields, loopers and params
// Other DC items such as for Featured Image already have a Featured Image URL directly
add_filter('cs_dynamic_content_acf', 'cx_supply_field_image', 999, 3 );
add_filter('cs_dynamic_content_looper', 'cx_supply_field_image', 999, 3 );
add_filter('cs_dynamic_content_param', 'cx_supply_field_image', 999, 3 );
add_filter('cs_dynamic_content_p', 'cx_supply_field_image', 999, 3 );
add_filter('cs_dynamic_content_g', 'cx_supply_field_image', 999, 3 );

I’m posting here in case it might be useful for others, or if it potentially could be included into the core at some point.

Works perfectly well as an added filter in any Child Theme functions.php

2 Likes

Thanks for sharing, @arthurodb! Always love seeing how people are leveraging features like this. I’m sure the community will find this helpful in certain situations. :slight_smile: