The replace_uploaded_image()
function works great! I know it works because when I login to WP Admin and upload an image, it does exactly what it is supposed to do. Furthermore, if I remove the function and go upload an image, the original uploaded image is there. (exactly what you would expect.)
I'm trying to see the contents of the variables within the function. I'm stumped about why it seems to execute all the code except the write_log()
parts.
The custom_gallery function works and I have no problems there. I only included it to illustrate the fact that using write_log()
within that function works fine.
The only time write_log()
doesn't work is when called from within replace_uploaded_image()
.
Any clue why it is like that?
<?php
/**
* Replace default gallery HTML with my own.
*/
function custom_gallery ( $output, $attr ) {
// Do some stuff
// A bunch of code that works good.
write_log ( 'test' ); // Writing string from here works.
write_log( $object ); // writing array or object from here works.
return $output;
}
add_filter( 'post_gallery', 'custom_gallery', 10, 2 );
/**
* Delete the original uploaded image and use the large format in its place.
*/
function replace_uploaded_image ( $image_data ) {
write_log ( 'test' ); // Nothing appears in error_log
write_log ( $image_data ); // Nothing appears in error_log
// if there is no large image : return
if ( !isset ( $image_data['sizes']['large'] ) ) return $image_data;
// paths to the uploaded image and the large image
$upload_dir = wp_upload_dir();
$uploaded_image_location = $upload_dir['basedir'] . '/' . $image_data['file'];
$current_subdir = substr( $image_data['file'], 0, strrpos($image_data['file'], '/' ) );
$large_image_location = $upload_dir['basedir'] . '/' . $current_subdir . '/' . $image_data['sizes']['large']['file'];
// delete the uploaded image
unlink( $uploaded_image_location );
// rename the large image
rename( $large_image_location, $uploaded_image_location );
// update image metadata and return them
$image_data['width'] = $image_data['sizes']['large']['width'];
$image_data['height'] = $image_data['sizes']['large']['height'];
unset( $image_data['sizes']['large'] );
write_log ( 'test' ); // Nothing appears in error_log
write_log ( $image_data ); // Nothing appears in error_log
return $image_data;
}
add_filter( 'wp_generate_attachment_metadata', 'replace_uploaded_image' );
// for debugging. write to error log.
if ( !function_exists( 'write_log' ) ) {
function write_log ( $log ) {
if ( true === WP_DEBUG ) {
error_log( '******************************' );
if ( is_array( $log ) || is_object( $log ) ) {
error_log( print_r( $log, true ) );
} else {
error_log( $log );
}
}
}
}
?>