@@ -52,11 +52,18 @@ public function __construct() {
5252 /**
5353 * Hooks after user init
5454 *
55- * @since 7.2
55+ * @since 7.2
56+ * @since 7.4 Add media replace original with scaled.
5657 */
5758 public function after_user_init () {
5859 // Hook to attachment delete action (PR#844, Issue#841) for AJAX del compatibility
5960 add_action ('delete_attachment ' , array ( $ this , 'delete_attachment ' ), 11 , 2 );
61+
62+ // For big images, allow to replace original with scaled image.
63+ if ( $ this ->conf (Base::O_MEDIA_REP_W_SCALED ) ){
64+ // Added priority 9 to happen before other functions added.
65+ add_filter ('wp_update_attachment_metadata ' , array ( $ this , 'replace_original_with_scaled ' ), 9 , 2 );
66+ }
6067 }
6168
6269 /**
@@ -98,6 +105,47 @@ public function init() {
98105 add_filter ('litespeed_optm_html_head ' , array ( $ this , 'finalize_head ' ));
99106 }
100107
108+ /**
109+ * Handle attachment create
110+ *
111+ * @param array $metadata Current meta array.
112+ * @param int $attachment_id Attachment ID.
113+ * @return array $metadata
114+ * @since 7.4
115+ */
116+ public function replace_original_with_scaled ( $ metadata , $ attachment_id ) {
117+ // Test if create and image was resized.
118+ if ( $ metadata && isset ($ metadata ['original_image ' ]) && isset ($ metadata ['file ' ]) && false !== strstr ($ metadata ['file ' ], '-scaled ' )){
119+ // Get rescaled file name.
120+ $ path_exploded = explode ( '/ ' , strrev ($ metadata ['file ' ]), 2 );
121+ $ rescaled_file_name = strrev ($ path_exploded [0 ]);
122+
123+ // Create paths for images: resized and original.
124+ $ base_path = $ this ->_wp_upload_dir ['basedir ' ] . $ this ->_wp_upload_dir ['subdir ' ] . '/ ' ;
125+ $ rescaled_path = $ base_path . $ rescaled_file_name ;
126+ $ new_path = $ base_path . $ metadata ['original_image ' ];
127+
128+ if ( file_exists ( $ rescaled_path ) && file_exists ( $ new_path ) ){
129+ // Move rescaled to original.
130+ rename ( $ rescaled_path , $ new_path );
131+
132+ // Change array file key.
133+ $ metadata ['file ' ] = $ this ->_wp_upload_dir ['subdir ' ] . '/ ' . $ metadata ['original_image ' ];
134+ if ( 0 === strpos ( $ metadata ['file ' ], '/ ' ) ){
135+ $ metadata ['file ' ] = substr ( $ metadata ['file ' ], 1 );
136+ }
137+
138+ // Delete array "original_image" key.
139+ unset($ metadata ['original_image ' ]);
140+
141+ // Update meta "_wp_attached_file".
142+ update_post_meta ( $ attachment_id , '_wp_attached_file ' , $ metadata ['file ' ] );
143+ }
144+ }
145+
146+ return $ metadata ;
147+ }
148+
101149 /**
102150 * Add featured image to head
103151 */
0 commit comments