Now that WordPress has Responsive Images as part of core, here’s how to use that power along side Advanced Custom Fields:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php // Get Image url (for background) ?> | |
<?php $bgImage = esc_html(get_field('img_field')); ?> | |
<?php $bgURL = wp_get_attachment_image_src($bgImage, 'full'); ?> | |
<div class="bg" style="background-image: url(<?php echo $bgURL[0]; ?>);"></div> | |
<?php // Get Image attatchment (for full image output) ?> | |
<?php $bpImage = esc_html(get_field('img_field')); ?> | |
<?php echo wp_get_attachment_image($bpImage, 'full'); ?> |
A couple of notes
1. Use Image ID as ACF Return Value:
2. I’ve begun escaping the data output from ACF. I thought that since it’s an image url that we’re ultimately after, esc_url
would be appropriate according to this Codex article on Validating Sanitizing and Escaping User Data but it doesn’t appear to output anything. Perhaps it’s because the data we’re grabbing is the ID of an attachment…