Skip to content

Instantly share code, notes, and snippets.

@webcraftsman
Last active September 9, 2021 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webcraftsman/6efdf0c99aedc492c1aeb8beeac1a667 to your computer and use it in GitHub Desktop.
Save webcraftsman/6efdf0c99aedc492c1aeb8beeac1a667 to your computer and use it in GitHub Desktop.
Solution to upload 2x image to WordPress with ACF field and have WordPress generate 1x image
// This code was written by Ryan McCahan with input from me, Jeff Bridgforth.
// This code goes into functions.php in your theme. The ACF must have 2x in the label. This code looks for that in the ACF label and generates the 1x image
add_filter('intermediate_image_sizes_advanced', function($new_sizes, $image_meta, $attachment_id){
if (isset($_POST['_acfuploader']) && stristr(get_field_object($_POST['_acfuploader'])['label'], '2x') !== false) {
return [
'image-1x' => [
'width' => ceil($image_meta['width'] / 2),
'height' => 0,
'crop' => false,
]
];
}
return $new_sizes;
}, 10, 3);
// Code to grab the 1x image
function get1xImage($image) {
$attachment = wp_get_attachment_metadata($image['ID']);
if (isset($attachment['sizes']) && isset($attachment['sizes']['image-1x'])) {
$filename = basename($attachment['file']);
$url = str_replace($filename, $attachment['sizes']['image-1x']['file'], $attachment['file']);
return wp_get_upload_dir()['baseurl'] . '/' . $url;
} else {
return wp_get_upload_dir()['baseurl']. '/' . $image['file'];
}
}
// Function to display images in template
function get2xImage($field, $alt = false) {
ob_start();
?>
<img src="<?=get1xImage($field);?>" srcset="<?=$field['url']?> 2x" alt="<?=$alt === false ? $field['alt'] : $alt ?>" width="<?php echo $field['width']/2;?>" height="<?php echo $field['height']/2;?>" />
<?php
return ob_get_clean();
}
// This code will be called in your template
<?=get2ximage(get_field('name_of_your_ACF_field')); ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment