Skip to content

Instantly share code, notes, and snippets.

@joshmoto
Created September 13, 2019 14:09
Show Gist options
  • Save joshmoto/067d5add17483d31543821252c3982c8 to your computer and use it in GitHub Desktop.
Save joshmoto/067d5add17483d31543821252c3982c8 to your computer and use it in GitHub Desktop.
Lazy loading images on admin columns for the acf-crop image field using instanceof ACA\ACF\Column
<?php
add_filter('ac/column/value', 'ac_product_img_lazy_loading', 10, 3 );
add_action('admin_footer', 'ac_product_img_lazy_loading_script');
function ac_product_img_lazy_loading( $value, $id, $column ) {
if ( $column instanceof ACA\ACF\Column ) {
$acf_type = $column->get_acf_field_option( 'type' ); // Get the ACF field type
$acf_value = $column->get_raw_value( $id );
if( 'image_crop' == $acf_type ){
if($acf_value) {
// decode the value
$value = json_decode($acf_value);
// get the image id
$img_id = $value->original_image;
// get the thumbnail image attachment src
$img = wp_get_attachment_image_src($img_id, 'thumbnail');
// new image value
$value = '<span class="ac-image loading" data-media-id="'.$img_id.'" data-img="'.$img[0].'"><img style="max-height:75px;max-width:75px;" src="'.includes_url().'/images/blank.gif" alt="" /></span>';
} else {
// empty value
$value = '';
}
}
}
// return the new value
return $value;
}
function ac_product_img_lazy_loading_script() {
?>
<script type="text/javascript">
(function($){
// the loading image var
var $img = $('.ac-image.loading', '.ac-product');
// lazy load the images in viewport
function lazy_load_images() {
// check the location of each image
$img.each( function(){
// viewport and image positioning vars
var bottom_of_img = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
// if the image is completely visible in the window
if( bottom_of_window > bottom_of_img ){
// remove the loading class
$(this).removeClass('loading');
// get the data-img value
var img = $(this).data('img');
// reset image src attr
$('IMG',this).attr('src',img);
}
});
}
// do function
lazy_load_images();
// on scroll
$(window).scroll(function() {
// do function
lazy_load_images();
});
})(jQuery);
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment