画像パスを取得し、その末尾にテキストを追加してから、結合する関数を作成しました。画像に新しいテキストを追加した後、ファイルが存在するかどうかをテストするためにifelseブランチを作成しようとしています。
たとえば、画像パスをリクエストした場合:
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」のようなルートスタイルの絶対パスのみを受け入れますか?