Support

Account

Home Forums Feature Requests Choose what size 'Image URL' returns

Solved

Choose what size 'Image URL' returns

  • I like the convenience of having the Image field type return the Image URL, but most of the time I don’t want the full size. I’ll usually either have a custom image size set up or I just want the image to shrink to fit, and in the latter case I still don’t need the full size image bogging down the page load, so I just pick a smaller size like the large or medium to save on memory.

    I think when ‘Return Value’ is set to ‘Image URL’ you should be able to choose the size that the URL returns.

  • Suggestions like this should be submitted here https://www.advancedcustomfields.com/contact/, I know, the title of the forum is Feature Requests… long story.

    As for a solution that can be used now. Generally when I want other that the full size image I get the image ID and then use wp_get_attachment_image_src();

    
    $image_id = get_field('image_field_name', false, false);
    $image = wp_get_attachment_image_src($image_id, 'size i want');
    echo $image[0];
    
  • Ah, I’ll be sure to submit it there then.

    I do know of that solution, but as you can see it just requires more code than feels necessary when I could just use…

    the_field( 'image_field_name' );

    And have it return exactly what I need.

  • You can do that by

    1) Create a custom custom field setting https://www.advancedcustomfields.com/resources/adding-custom-settings-fields/ that uses a radio field, you’ll probably need to get the existing image sizes, don’t know how to do that off the top of my head.

    2) Creating an acf/format_value filter https://www.advancedcustomfields.com/resources/acf-format_value/ that returns the URL based on the custom setting.

  • I was actually just looking into something like that, thanks!

    Is there a way to specify where the custom field setting should be placed? For example, place it directly after the Return Format setting?

  • The changes aren’t that granular. You can either place it at the beginning of the options, right after the required setting or the end. Or at the end, which I think is just before the conditional logic setting.

  • A simple solution if the goal is to keep templates clean would be to create a helper function like

    function get_image_field_src_by_size($field_name, $size){
        
        $image_id = get_field($field_name);
        $image = wp_get_attachment_image_src($image_id, $size);
        return $image[0];
    }
    
    <div style="background-image:url(<?php echo get_image_field_src_by_size('image_field_name', 'image_size_name') ?>)"></div>
    

    Or, without a function and just a bit uglier inline

    <div style="background-image:url(<?php echo wp_get_attachment_image_src(get_field('image_field_name'), 'image_size_name')[0] ?>)"></div>

Viewing 7 posts - 1 through 7 (of 7 total)

You must be logged in to reply to this topic.