To modify the media – when Delete local file
option is enabled – the original file will need to be fetched from S3 and uploaded back to the S3 once altered.
Below is the custom code which will do the job. It can be added to theme’s functions.php
file.
/**
* When 'Delete local file' option is on in rtAmazon S3 plugin,
* Fetch the original image from S3 bucket and Upload back the filtered photos
* to the S3 bucket
*/
function custom_rtmedia_photo_filter_compatibility() {
if ( ! class_exists( 'RTAWSS3_Client' ) ) {
return false;
}
if ( defined( 'RTAWSS3_ACCESS_KEY_ID' ) && defined( 'RTAWSS3_SECRET_ACCESS_KEY' ) ) {
$rtawss3_default_option = array();
$rtawss3_default_option['rtawss3_access_key_id'] = RTAWSS3_ACCESS_KEY_ID;
$rtawss3_default_option['rtawss3_secret_access_key'] = RTAWSS3_SECRET_ACCESS_KEY;
} else {
if ( is_multisite() ) {
$rtawss3_default_option = get_option( 'rtawss3-default-options' );
} else {
$rtawss3_default_option = get_site_option( 'rtawss3-default-options' );
}
}
$bucket = rtamazon_s3_get_bucket_name();
$rtawss3_client = new RTAWSS3_Client();
$rtawss3_bucket_location = $rtawss3_client->rtawss3_get_bucket_location( $bucket );
$unlink = rtamazon_s3_is_delete_local_file_allowed( $bucket );
if ( isset( $rtawss3_default_option['rtawss3_access_key_id'] ) && isset( $rtawss3_default_option['rtawss3_secret_access_key'] ) && false !== $bucket && ! is_wp_error( $rtawss3_bucket_location ) && $unlink ) {
add_action( 'rtmedia_before_update_media', 'custom_rtmedia_before_create_instagram_thumbs', 1, 1 );
add_action( 'rtmedia_after_update_media', 'custom_rtmedia_after_create_instagram_thumbs', 99999, 1 );
}
}
add_action( 'init', 'custom_rtmedia_photo_filter_compatibility' );
// Fetch the media from the S3 bucket
function custom_rtmedia_before_create_instagram_thumbs( $media_id ) {
//Get the file
$wp_folder = wp_upload_dir();
$base_dir = $wp_folder['basedir'];
$attached_file = get_post_meta( rtmedia_media_id( $media_id ), '_wp_attached_file', true );
$image_path = $base_dir . '/' . $attached_file;
if ( ! file_exists( $image_path ) ) {
$image_url = wp_get_attachment_url( rtmedia_media_id( $media_id ) );
$content = file_get_contents( $image_url );
//Store in the filesystem.
$file_pointer = fopen( get_attached_file( rtmedia_media_id( $media_id ) ), 'w' );
fwrite( $file_pointer, $content );
fclose( $file_pointer );
}
}
// Delete the media after modification is done
function custom_rtmedia_after_create_instagram_thumbs( $media_id ) {
$file = get_attached_file( rtmedia_media_id( $media_id ) );
if ( ! empty( $file ) && file_exists( $file ) ) {
@unlink( $file );
}
}