@@ -2192,4 +2192,47 @@ public function handler() {
21922192
21932193 Admin::redirect ();
21942194 }
2195+
2196+ /**
2197+ * Replace original with scaled image.
2198+ *
2199+ * @since 7.4
2200+ * @param array $meta_value Current meta array.
2201+ * @param int $post_id Attachment ID.
2202+ * @param string $context Can be "create" or "update".
2203+ * @return array $meta_value
2204+ * @access public
2205+ */
2206+ public function replace_original_with_scaled ( $ meta_value , $ post_id , $ context ) {
2207+ // Test if create and image was resized.
2208+ if ( "create " === $ context && isset ($ meta_value ['original_image ' ]) && isset ($ meta_value ['file ' ]) && false !== strstr ($ meta_value ['file ' ], '-scaled ' )){
2209+ $ media_path = wp_upload_dir ();
2210+ // Get rescaled file name.
2211+ $ path_exploded = explode ( DIRECTORY_SEPARATOR , strrev ($ meta_value ['file ' ]), 2 );
2212+ $ rescaled_file_name = strrev ($ path_exploded [0 ]);
2213+
2214+ // Create paths for images: resized and original.
2215+ $ rescaled_path = $ media_path ['basedir ' ] . $ media_path ['subdir ' ] . DIRECTORY_SEPARATOR . $ rescaled_file_name ;
2216+ $ new_path = $ media_path ['basedir ' ] . $ media_path ['subdir ' ] . DIRECTORY_SEPARATOR . $ meta_value ['original_image ' ];
2217+
2218+ if ( is_file ( $ rescaled_path ) && is_file ( $ rescaled_path ) ){
2219+ // Move rescaled to original.
2220+ rename ( $ rescaled_path , $ new_path );
2221+
2222+ // Change array file key.
2223+ $ meta_value ['file ' ] = $ media_path ['subdir ' ] . DIRECTORY_SEPARATOR . $ meta_value ['original_image ' ];
2224+ if ( 0 === strpos ( $ meta_value ['file ' ], DIRECTORY_SEPARATOR ) ){
2225+ $ meta_value ['file ' ] = substr ( $ meta_value ['file ' ], 1 );
2226+ }
2227+
2228+ // Delete array "original_image" key.
2229+ unset($ meta_value ['original_image ' ]);
2230+
2231+ // Update meta "_wp_attached_file".
2232+ update_post_meta ( $ post_id , '_wp_attached_file ' , $ meta_value ['file ' ] );
2233+ }
2234+ }
2235+
2236+ return $ meta_value ;
2237+ }
21952238}
0 commit comments