早上好
我正在尝试更改Wordpress用于重命名上载文件的名称格式。当我上传一张文件名为“沙漠景观.jpg”的图像时,Wordpress将设置缩放版本,并将文件名重命名为“沙漠景观-{WIDTHxHEIGHT}.jpg”(按缩略图大小倾斜)的不同组合。
是否有方法删除宽度(&a);从文件名中删除高度属性,并将其替换为“{medium}-沙漠景观.jpg”、“{large}-沙漠景观.jpg”和“{small}-沙漠景观.jpg”?
一直在看这个帖子Rename image uploads with width in filename 我无法用正确的方法修复它。
非常感谢。
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( \'image_make_intermediate_size\', \'rename_intermediates_wpse_82193\' );
function rename_intermediates_wpse_82193( $image )
{
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info[\'dirname\'] . \'/\';
$ext = \'.\' . $info[\'extension\'];
$name = wp_basename( $image, "$ext" );
// Build our new image name
$name_prefix = substr( $name, 0, strrpos( $name, \'-\' ) );
$size_extension = substr( $name, strrpos( $name, \'-\' ) + 1 );
$new_name = $dir . $size_extension . \'-\' . $name_prefix . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
最合适的回答,由SO网友:Nicolai Grossherr 整理而成
老实说,我有点困惑,你到目前为止所做的一切都是抄袭&;粘贴答案不会解决您的问题。另一方面,你清楚地描述了你的问题。下面我为您概述了一个解决方案,如果您真的想了解发生了什么,请查看其他注释和信息源。
Code:
// The filter runs when resizing an image to make a thumbnail or intermediate size.
add_filter( \'image_make_intermediate_size\', \'wpse_123240_rename_intermediates\' );
function wpse_123240_rename_intermediates( $image ) {
// Split the $image path into directory/extension/name
$info = pathinfo($image);
$dir = $info[\'dirname\'] . \'/\';
$ext = \'.\' . $info[\'extension\'];
$name = wp_basename( $image, "$ext" );
// Get image information
// Image edtor is used for this
$img = wp_get_image_editor( $image );
// Get image size, width and height
$img_size = $img->get_size();
// Image prefix for builtin sizes
// Note: beware possible conflict with custom images sizes with the same width
$widths = [];
$size_based_img_name_prefix = \'\';
foreach ( get_intermediate_image_sizes() as $_size ) {
if ( in_array( $_size, [ \'thumbnail\', \'medium\', \'medium_large\', \'large\' ] ) ) {
$width = get_option( "{$_size}_size_w" );
if ( ! isset( $widths[ $width ] ) ) {
$widths[ $width ] = $_size;
}
}
}
if ( array_key_exists( $img_size[ \'width\' ], $widths ) ) {
$size_based_img_name_prefix = $widths[ $img_size[\'width\'] ] . \'-\';
$name_prefix = substr( $name, 0, strrpos( $name, \'-\' ) );
} else {
$name_prefix = $name;
}
// Build our new image name
$new_name = $dir . $size_based_img_name_prefix . $name_prefix . $ext;
// Rename the intermediate size
$did_it = rename( $image, $new_name );
// Renaming successful, return new name
if( $did_it )
return $new_name;
return $image;
}
Information Sources:
注:未经测试