Last active
September 13, 2019 14:09
-
-
Save joshmoto/8ecd3aa0a166c300611a32026540b9bc to your computer and use it in GitHub Desktop.
Lazy loading images on admin columns for the acf-crop image field using instanceof ACP\Column\CustomField
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 | |
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 the column is custom field instance | |
if ( $column instanceof ACP\Column\CustomField ) { | |
// get the meta key | |
$meta_key = $column->get_meta_key(); | |
// if product featured image | |
if ( 'product_featured_image' == $meta_key ) { | |
// if value string length is 7, basically false | |
if(strlen($value) === 7) { | |
// empty value | |
$value = ''; | |
} else { | |
// decode the value | |
$value = json_decode($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'); | |
// get the thumbnail image url | |
$img_url = $img[0]; | |
// new image value | |
$value = '<span class="ac-image loading" data-media-id="'.$img_id.'" data-img="'.$img_url.'"><img style="max-height:75px;max-width:75px;" src="'.includes_url().'/images/blank.gif" alt="" /></span>'; | |
} | |
} | |
} | |
// 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