-
-
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 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
// 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