【发布时间】:2011-06-21 14:46:47
【问题描述】:
我编写了一个函数来获取图像路径,在其末尾添加一些文本,然后将其重新组合在一起。在将新文本附加到图像后,我正在尝试编写一个 if else 分支来测试文件是否存在。
比如我请求图片路径:
http://example.com/image1.jpg
可以改成这样:
http://example.com/image1-150x100.jpg
该函数是为 WordPress 设计的,因此需要 $post->ID 参数、自定义字段名称、预期目标的宽度和高度。
函数如下:
function get_galleria_image ( $post_id, $customFieldName, $width, $height ) {
$imagePath = get_post_meta($post_id, $customFieldName, true);
$splitImage = explode('.', $imagePath);
$count = count($splitImage);
$firstHalf = array_slice($splitImage, 0, $count-1);
$secondHalf = array_slice($splitImage, $count-1);
$secondHalf[0] = '-' . $width . 'x' . $height . '.' . $secondHalf[0];
$firstHalfJoined = implode('.', $firstHalf);
$completedString = $firstHalfJoined . $secondHalf[0];
// if the filename with the joined string does not exist, return the original image
if (file_exists($completedString)){
return $completedString;
} else {
return $imagePath;
}
}
我知道这很粗糙,因此欢迎任何压缩此代码并使其“更好”的想法。我发现该函数始终返回原始图像路径。 file_exists() 可以采用像“http://example.com/image1.jpg”这样的绝对路径,还是只接受根风格的绝对路径,如“/path/to/file/image1.jpg”?
【问题讨论】:
标签: php wordpress file-exists