Created
August 23, 2025 11:37
-
-
Save plugin-republic/673a591e596efb3fe36ae24b2b34fd54 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* Move uploaded images to media library and thence to third-party storage like Amazon S3 etc | |
*/ | |
add_filter( 'pewc_offload_media', '__return_true' ); | |
function demo_upload_image( $uploaded_files ) { | |
$moved_files = array(); | |
$delete_files = array(); | |
if( $uploaded_files ) { | |
foreach( $uploaded_files as $index=>$upload ) { | |
$moved_files[$index] = $upload; | |
// Create the full URL | |
$url = get_site_url() . $upload['url']; | |
// Ensure we don't generate all the different media sizes for this upload | |
add_filter( 'intermediate_image_sizes_advanced', '__return_empty_array' ); | |
// Move the upload to the media library | |
$id = media_handle_sideload( $moved_files[$index], 0 ); | |
$moved_files[$index]['file'] = get_attached_file( $id ); | |
$moved_files[$index]['url'] = wp_get_attachment_url( $id ); | |
// If error storing permanently, unlink | |
if ( is_wp_error( $id ) ) { | |
// Something went wrong | |
@unlink( $upload['file'] ); | |
return $uploaded_files; | |
} else { | |
// Clear the upload file and any temporary files from the original directory | |
$delete_files[] = $upload['file']; | |
$delete_files[] = $moved_files[$index]['file']; | |
} | |
} | |
} | |
if( $delete_files ) { | |
foreach( $delete_files as $delete_file ) { | |
@unlink( $delete_file ); | |
} | |
} | |
return $moved_files; | |
} | |
function demo_move_uploads_to_media_library( $uploaded_files, $post_obj ) { | |
if( apply_filters( 'pewc_offload_media', false ) ) { | |
$uploaded_files = demo_upload_image( $uploaded_files ); | |
} | |
return $uploaded_files; | |
} | |
add_filter( 'pewc_after_ajax_upload', 'demo_move_uploads_to_media_library', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment