这个replace_uploaded_image()
功能非常好!我知道这是可行的,因为当我登录到WP Admin并上传一个图像时,它完全按照它应该做的做。此外,如果我删除该功能并上传图像,则原始上传的图像就在那里。(正是您所期望的。)
我试图查看函数中变量的内容。我很困惑为什么它似乎能执行所有的代码except 这个write_log()
零件。
custom\\u gallery功能正常,我在那里没有问题。我只是为了说明使用write_log()
在该功能内工作正常。
这个only 时间write_log()
从内部调用时不起作用replace_uploaded_image()
.
你知道为什么会这样吗?
<?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 );
}
}
}
}
?>