ACF Image Field Shortcode
Adds an [acf_image name="hero" size="large"] shortcode that outputs a responsive image from an ACF image field, whatever return format the field uses.
Opens WPIDE on
Code
add_shortcode( 'acf_image', function ( $atts ) {
$atts = shortcode_atts( array( 'name' => '', 'size' => 'large', 'post_id' => 0, 'class' => '' ), $atts, 'acf_image' );
$post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
if ( ! $post_id || ! function_exists( 'get_field' ) || ! is_post_publicly_viewable( $post_id ) ) {
return '';
}
$value = get_field( sanitize_key( $atts['name'] ), $post_id, false ); // Raw value: the attachment ID.
$id = is_array( $value ) ? (int) ( $value['ID'] ?? 0 ) : absint( $value );
if ( ! $id ) {
return '';
}
return wp_get_attachment_image( $id, sanitize_key( $atts['size'] ), false, array( 'class' => sanitize_html_class( $atts['class'] ) ) );
} );
Notes
The image's alt text comes from the Media Library. Add class="..." for styling.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.