Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Last active October 23, 2017 08:01
Show Gist options
  • Save BhargavBhandari90/26890fd087537d2360f4ba924a47a3e4 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/26890fd087537d2360f4ba924a47a3e4 to your computer and use it in GitHub Desktop.
Change srcset when rtAmazon-s3 plugin is active. Use at your own RISK.
<?php
/**
* Add this function into theme's functions.php
*
* This function will replace domain with amazon s3 bucket url for image's srcset.
*/
function rtawss3_wp_calculate_image_srcset_latin( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
if ( ! class_exists( 'RTAWSS3_Class' ) ) {
return;
}
// Get keys from rtAmazon setting.
$rtawss3 = RTAWSS3_Class::instance();
$rtawss3_default_option = $rtawss3->rtawss3_get_access_keys();
// If keys are not added, then no need to proceed.
if ( empty( $rtawss3_default_option ) ) {
return;
}
// Where clause for query.
$where = array(
'parent_id' => intval( $attachment_id ),
);
// Get cached data.
$rows = wp_cache_get( 'rt_amazon_s3_srcset_query_' . $attachment_id );
// Get thumbs.
if( false === $rows ) {
$rows = $rtawss3->rtawss3_db( 'get_results', array(), 'status', 'moved', false, array(), $where );
wp_cache_set( 'rt_amazon_s3_srcset_query_' . $attachment_id, $rows, '', WEEK_IN_SECONDS );
}
// total image sizes.
$image_sizes = $image_meta['sizes'];
// Get cached data.
$sources_new = wp_cache_get( 'rt_amazon_s3_source_' . $attachment_id );
// Get new srcset.
if ( is_array( $image_sizes ) && ! empty( $image_sizes ) && false === $sources_new ) {
foreach ( $image_sizes as $key => $value ) {
foreach ( $rows as $row ) {
if ( $key === $row->media_size && ! empty( $row->s3_url ) ) {
$sources_new[ $value['width'] ] = array(
'url' => $row->s3_url,
'descriptor' => 'x',
'value' => $value['width'],
);
}
}
}
// Set data into cache.
wp_cache_set( 'rt_amazon_s3_source_' . $attachment_id, $sources_new, '', WEEK_IN_SECONDS );
}
if ( empty( $sources_new ) ) {
return $sources;
}
return $sources_new;
}
add_filter( 'wp_calculate_image_srcset', 'rtawss3_wp_calculate_image_srcset_latin', 99, 5 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment