WordPress Snippet: Using ACF image and WordPress Featured Thumbnails

When building WordPress themes, there is often a need to use a featured thumbnail, or image value from ACF; as either a background image or as a <img> tag.

This snippet below is something I use frequently, hopefully this will be as benefit for you too.

    //Custom image sizes - Add these to your functions.php
    add_image_size( 'custom_image_size_1', 650, 650, false );
    add_image_size( 'custom_image_size_2', 300, 300, false );

<!-- BG IMAGES -->

<!-- WordPress ACF images as BG (ACF image fields must output as an array) -->
<div style="<?php $image = wp_get_attachment_image_src(get_field('your_acf_field_name')['ID'], 'custom_image_size_1')[0]; echo ($image ? ' background-image:url(\''.$image.'\');' : 'null' ); ?>"></div>

<!-- WordPress featured images as BG -->
<div style="<?php $image = get_the_post_thumbnail_url(get_the_ID(), 'custom_image_size_2'); echo ($image ? ' background-image:url(\''.$image.'\');' : 'null' ); ?>"></div>

<!-- IMG TAGS -->

<!-- WordPress ACF images as IMG (ACF image fields must output as an array) -->
    if ( $image = get_field('your_acf_field_name')['ID'] ) :
        echo wp_get_attachment_image( $image, 'custom_image_size_1', false, array('class' => 'custom_class_name_here') );

<!-- WordPress featured images as IMG -->
    if ( has_post_thumbnail() ) :
        echo get_the_post_thumbnail( 'custom_image_size_2', array('class' => 'custom_class_name_here') );

Or view as a Gist on Github:

There are no comments, be the first. Use the form below to add your comment

Post a Comment